Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>package org.mockitoutil;
import junit.framework.Assert;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public abstract class SimpleSerializationUtil {
//TODO use widely
public static <T> T serializeAndBack(T obj) throws Exception {
ByteArrayOutputStream os = serializeMock(obj);
return (T) deserializeMock(os, Object.class);
}
public static <T> T deserializeMock(ByteArrayOutputStream serialized, Class<T> type) throws IOException,
ClassNotFoundException {
InputStream unserialize = new ByteArrayInputStream(serialized.toByteArray());
return deserializeMock(unserialize, type);
}
public static <T> T deserializeMock(InputStream unserialize, Class<T> type) throws IOException, ClassNotFoundException {
Object readObject = new ObjectInputStream(unserialize).readObject();
Assert.assertNotNull(readObject);
return type.cast(readObject);
}
public static ByteArrayOutputStream serializeMock(Object mock) throws IOException {
ByteArrayOutputStream serialized = new ByteArrayOutputStream();
new ObjectOutputStream(serialized).writeObject(mock);
return serialized;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation.jmock;
import org.mockito.cglib.core.CodeGenerationException;
import org.mockito.cglib.core.NamingPolicy;
import org.mockito.cglib.core.Predicate;
import org.mockito.cglib.proxy.*;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.configuration.GlobalConfiguration;
import org.mockito.internal.creation.cglib.MockitoNamingPolicy;
import org.objenesis.ObjenesisStd;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.List;
import static org.mockito.internal.util.StringJoiner.join;
/**
* Thanks to jMock guys for this handy class that wraps all the cglib magic.
*/
public class ClassImposterizer {
public static final ClassImposterizer INSTANCE = new ClassImposterizer();
private ClassImposterizer() {}
//TODO: in order to provide decent exception message when objenesis is not found,
//have a constructor in this class that tries to instantiate ObjenesisStd and if it fails then show decent exception that dependency is missing
//TODO: for the same reason catch and give better feedback when hamcrest core is not found.
private ObjenesisStd objenesis = new ObjenesisStd(new GlobalConfiguration().enableClassCache());
private static final NamingPolicy NAMING_POLICY_THAT_ALLOWS_IMPOSTERISATION_OF_CLASSES_IN_SIGNED_PACKAGES = new MockitoNamingPolicy() {
@Override
public String getClassName(String prefix, String source, Object key, Predicate names) {
return "codegen." + super.getClassName(prefix, source, key, names);
}
};
private static final CallbackFilter IGNORE_BRIDGE_METHODS = new CallbackFilter() {
public int accept(Method method) {
return method.isBridge() ? 1 : 0;
}
};
public <T> T imp
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>osterise(final MethodInterceptor interceptor, Class<T> mockedType, Collection<Class> ancillaryTypes) {
return imposterise(interceptor, mockedType, ancillaryTypes.toArray(new Class[ancillaryTypes.size()]));
}
public <T> T imposterise(final MethodInterceptor interceptor, Class<T> mockedType, Class<?>... ancillaryTypes) {
Class<?> proxyClass = null;
Object proxyInstance = null;
try {
setConstructorsAccessible(mockedType, true);
proxyClass = createProxyClass(mockedType, ancillaryTypes);
proxyInstance = createProxy(proxyClass, interceptor);
return mockedType.cast(proxyInstance);
} catch (ClassCastException cce) {
// NPE unlikely to happen because CCE will only happen on the cast statement
throw new MockitoException(join(
"ClassCastException occurred while creating the mockito proxy :",
" class to imposterize : '" + mockedType.getCanonicalName() + "', loaded by classloader : '" + mockedType.getClassLoader() + "'",
" imposterizing class : '" + proxyClass.getCanonicalName() + "', loaded by classloader : '" + proxyClass.getClassLoader() + "'",
" proxy instance class : '" + proxyInstance.getClass().getCanonicalName() + "', loaded by classloader : '" + proxyInstance.getClass().getClassLoader() + "'",
"",
"You might experience classloading issues, disabling the Objenesis cache *might* help (see MockitoConfiguration)"
), cce);
} finally {
setConstructorsAccessible(mockedType, false);
}
}
public void setConstructorsAccessible(Class<?> mockedType, boolean accessible) {
for (Constructor<?> constructor : mockedType.getDeclaredConstructors()) {
constructor.setAccessible(accessible);
}
}
public Class<?> createProxyClass(Class<?> mockedType, Class<?>... interfaces) {
if (mockedType == Object.class) {
mockedType = ClassWithSuperclassToWorkAroundCglibBug.class;
}
Enhancer enhancer = new Enhancer() {
@Override
@SuppressWarnings("unchecked")
protected void filterConstructors(Class sc, List constructors) {
// Don't filter
}
};
Class<?>[] allMockedTypes = prepend(mockedType, interfaces);
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>enhancer.setClassLoader(SearchingClassLoader.combineLoadersOf(allMockedTypes));
enhancer.setUseFactory(true);
if (mockedType.isInterface()) {
enhancer.setSuperclass(Object.class);
enhancer.setInterfaces(allMockedTypes);
} else {
enhancer.setSuperclass(mockedType);
enhancer.setInterfaces(interfaces);
}
enhancer.setCallbackTypes(new Class[]{MethodInterceptor.class, NoOp.class});
enhancer.setCallbackFilter(IGNORE_BRIDGE_METHODS);
if (mockedType.getSigners() != null) {
enhancer.setNamingPolicy(NAMING_POLICY_THAT_ALLOWS_IMPOSTERISATION_OF_CLASSES_IN_SIGNED_PACKAGES);
} else {
enhancer.setNamingPolicy(MockitoNamingPolicy.INSTANCE);
}
enhancer.setSerialVersionUID(42L);
try {
return enhancer.createClass();
} catch (CodeGenerationException e) {
if (Modifier.isPrivate(mockedType.getModifiers())) {
throw new MockitoException("\n"
+ "Mockito cannot mock this class: " + mockedType
+ ".\n"
+ "Most likely it is a private class that is not visible by Mockito");
}
throw new MockitoException("\n"
+ "Mockito cannot mock this class: " + mockedType
+ "\n"
+ "Mockito can only mock visible & non-final classes."
+ "\n"
+ "If you're not sure why you're getting this error, please report to the mailing list.", e);
}
}
private Object createProxy(Class<?> proxyClass, final MethodInterceptor interceptor) {
Factory proxy = (Factory) objenesis.newInstance(proxyClass);
proxy.setCallbacks(new Callback[] {interceptor, SerializableNoOp.SERIALIZABLE_INSTANCE });
return proxy;
}
private Class<?>[] prepend(Class<?> first, Class<?>... rest) {
Class<?>[] all = new Class<?>[rest.length+1];
all[0] = first;
System.arraycopy(rest, 0, all, 1, rest.length);
return all;
}
public static class ClassWithSuperclass
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> Sets a generic Answer for the method. E.g:
* <pre class="code"><code class="java">
* when(mock.someMethod(10)).thenAnswer(new Answer<Integer>() {
* public Integer answer(InvocationOnMock invocation) throws Throwable {
* return (Integer) invocation.getArguments()[0];
* }
* }
* </code></pre>
*
* @param answer the custom answer to execute.
*
* @return iOngoingStubbing object that allows stubbing consecutive calls
*/
OngoingStubbing<T> thenAnswer(Answer<?> answer);
/**
* Sets a generic Answer for the method.
*
* This method is an alias of {@link #thenAnswer(Answer)}. This alias allows
* more readable tests on occasion, for example:
* <pre class="code"><code class="java">
* //using 'then' alias:
* when(mock.foo()).then(returnCoolValue());
*
* //versus good old 'thenAnswer:
* when(mock.foo()).thenAnswer(byReturningCoolValue());
* </code></pre>
*
* @param answer the custom answer to execute.
* @return iOngoingStubbing object that allows stubbing consecutive calls
*
* @see #thenAnswer(Answer)
* @since 1.9.0
*/
OngoingStubbing<T> then(Answer<?> answer);
/**
* Returns the mock that was used for this stub.
* <p>
* It allows to create a stub in one line of code.
* This can be helpful to keep test code clean.
* For example, some boring stub can be created & stubbed at field initialization in a test:
* <pre class="code"><code class="java">
* public class CarTest {
* Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();
*
* @Test public void should... {}
* </code></pre>
*
* @param <M> The mock type given by the variable type.
* @return Mock used in this ongoing stubbing.
* @since 1.
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.answers;
import org.mockito.exceptions.Reporter;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
/**
* Returns the passed parameter identity at specified index.
*
* <p>The <code>argumentIndex</code> represents the index in the argument array of the invocation.</p>
* <p>If this number equals -1 then the last argument is returned.</p>
*
* @see org.mockito.AdditionalAnswers
* @since 1.9.5
*/
public class ReturnsArgumentAt implements Answer<Object>, Serializable {
private static final long serialVersionUID = -589315085166295101L;
public static final int LAST_ARGUMENT = -1;
private final int wantedArgumentPosition;
/**
* Build the identity answer to return the argument at the given position in the argument array.
*
* @param wantedArgumentPosition The position of the argument identity to return in the invocation.
* Using <code>-1</code> indicates the last argument.
*/
public ReturnsArgumentAt(int wantedArgumentPosition) {
this.wantedArgumentPosition = checkWithinAllowedRange(wantedArgumentPosition);
}
public Object answer(InvocationOnMock invocation) throws Throwable {
validateIndexWithinInvocationRange(invocation);
return invocation.getArguments()[actualArgumentPosition(invocation)];
}
private int actualArgumentPosition(InvocationOnMock invocation) {
return returningLastArg() ?
lastArgumentIndexOf(invocation) :
argumentIndexOf(invocation);
}
private boolean returningLastArg() {
return wantedArgumentPosition == LAST_ARGUMENT;
}
private int argumentIndexOf(InvocationOnMock invocation) {
return wantedArgumentPosition;
}
private int lastArgumentIndexOf(InvocationOnMock invocation) {
return invocation.getArguments().length - 1;
}
private int checkWithinAllowedRange(int argumentPosition) {
if (argumentPosition != LAST_ARGUMENT && argumentPosition < 0) {
new Reporter().invalidArgumentRangeAtIdentityAnswerCreationTime();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util;
import org.mockito.exceptions.Reporter;
import org.mockito.internal.util.reflection.Constructors;
import java.io.Serializable;
import java.util.Collection;
@SuppressWarnings("unchecked")
public class MockCreationValidator {
private final MockUtil mockUtil = new MockUtil();
public void validateType(Class classToMock) {
if (!mockUtil.isTypeMockable(classToMock)) {
new Reporter().cannotMockFinalClass(classToMock);
}
}
public void validateExtraInterfaces(Class classToMock, Collection<Class> extraInterfaces) {
if (extraInterfaces == null) {
return;
}
for (Class i : extraInterfaces) {
if (classToMock == i) {
new Reporter().extraInterfacesCannotContainMockedType(classToMock);
}
}
}
public void validateMockedType(Class classToMock, Object spiedInstance) {
if (classToMock == null || spiedInstance == null) {
return;
}
if (!classToMock.equals(spiedInstance.getClass())) {
new Reporter().mockedTypeIsInconsistentWithSpiedInstanceType(classToMock, spiedInstance);
}
}
public void validateDelegatedInstance(Class classToMock, Object delegatedInstance) {
if (classToMock == null || delegatedInstance == null) {
return;
}
if (delegatedInstance.getClass().isAssignableFrom(classToMock)) {
new Reporter().mockedTypeIsInconsistentWithDelegatedInstanceType(classToMock, delegatedInstance);
}
}
public void validateSerializable(Class classToMock, boolean serializable) {
// We can't catch all the errors with this piece of code
// Having a **superclass that do not implements Serializable** might fail as well when serialized
// Though it might prevent issues when mockito is mocking a class without superclass.
if(serializable
&& !classToMock.isInterface()
&& !(Serializable.class.isAssignableFrom(classToMock))
&& Constructors.noArgConstructorOf(classToMock) == null
) {
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> exclude, if field does not exist it is ignored.
* @return <code>null</code>.
*/
public static <T> T refEq(T value, String... excludeFields) {
return reportMatcher(new ReflectionEquals(value, excludeFields)).<T>returnNull();
}
/**
* Object argument that is the same as the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param <T>
* the type of the object, it is passed through to prevent casts.
* @param value
* the given value.
* @return <code>null</code>.
*/
public static <T> T same(T value) {
return (T) reportMatcher(new Same(value)).<T>returnFor(value);
}
/**
* <code>null</code> argument.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static Object isNull() {
return reportMatcher(Null.NULL).returnNull();
}
/**
* <code>null</code> argument.
* The class argument is provided to avoid casting.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param clazz Type to avoid casting
* @return <code>null</code>.
*/
public static <T> T isNull(Class<T> clazz) {
return (T) reportMatcher(Null.NULL).returnNull();
}
/**
* Not <code>null</code> argument.
* <p>
* alias to {@link Matchers#isNotNull()}
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static Object notNull() {
return reportMatcher(NotNull.NOT_NULL).returnNull();
}
/**
* Not <code>null</code> argument, not necessary of the given class.
* The class argument is provided to avoid casting.
* <p>
* alias to {@link Matchers#isNotNull(Class)}
* <p>
* See examples in javadoc for {@link Matchers} class
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>
*
* @param clazz Type to avoid casting
* @return <code>null</code>.
*/
public static <T> T notNull(Class<T> clazz) {
return (T) reportMatcher(NotNull.NOT_NULL).returnNull();
}
/**
* Not <code>null</code> argument.
* <p>
* alias to {@link Matchers#notNull()}
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static Object isNotNull() {
return notNull();
}
/**
* Not <code>null</code> argument, not necessary of the given class.
* The class argument is provided to avoid casting.
* <p>
* alias to {@link Matchers#notNull(Class)}
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param clazz Type to avoid casting
* @return <code>null</code>.
*/
public static <T> T isNotNull(Class<T> clazz) {
return notNull(clazz);
}
/**
* <code>String</code> argument that contains the given substring.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param substring
* the substring.
* @return empty String ("").
*/
public static String contains(String substring) {
return reportMatcher(new Contains(substring)).returnString();
}
/**
* <code>String</code> argument that matches the given regular expression.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param regex
* the regular expression.
* @return empty String ("").
*/
public static String matches(String regex) {
return reportMatcher(new Matches(regex)).returnString();
}
/**
* <code>String</code> argument that ends with the given suffix.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param suffix
* the suffix.
* @return empty String ("").
*/
public static String endsWith(String suffix) {
return reportMatcher(new EndsWith
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation.jmock;
import org.mockito.cglib.proxy.Callback;
import org.mockito.cglib.proxy.NoOp;
import java.io.Serializable;
/**
* Offer a Serializable implementation of the NoOp CGLIB callback.
*/
public class SerializableNoOp implements NoOp, Serializable {
private static final long serialVersionUID = 7434976328690189159L;
public static final Callback SERIALIZABLE_INSTANCE = new SerializableNoOp();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation;
import org.hamcrest.Matcher;
import org.mockito.internal.matchers.ArrayEquals;
import org.mockito.internal.matchers.Equals;
import org.mockito.internal.util.collections.ArrayUtils;
import java.util.ArrayList;
import java.util.List;
/**
* by Szczepan Faber, created at: 3/31/12
*/
public class ArgumentsProcessor {
// expands array varArgs that are given by runtime (1, [a, b]) into true
// varArgs (1, a, b);
public static Object[] expandVarArgs(final boolean isVarArgs, final Object[] args) {
if (!isVarArgs || new ArrayUtils().isEmpty(args) || args[args.length - 1] != null && !args[args.length - 1].getClass().isArray()) {
return args == null ? new Object[0] : args;
}
final int nonVarArgsCount = args.length - 1;
Object[] varArgs;
if (args[nonVarArgsCount] == null) {
// in case someone deliberately passed null varArg array
varArgs = new Object[] { null };
} else {
varArgs = ArrayEquals.createObjectArray(args[nonVarArgsCount]);
}
final int varArgsCount = varArgs.length;
Object[] newArgs = new Object[nonVarArgsCount + varArgsCount];
System.arraycopy(args, 0, newArgs, 0, nonVarArgsCount);
System.arraycopy(varArgs, 0, newArgs, nonVarArgsCount, varArgsCount);
return newArgs;
}
public static List<Matcher> argumentsToMatchers(Object[] arguments) {
List<Matcher> matchers = new ArrayList<Matcher>(arguments.length);
for (Object arg : arguments) {
if (arg != null && arg.getClass().isArray()) {
matchers.add(new ArrayEquals(arg));
} else {
matchers.add(new Equals(arg));
}
}
return matchers;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation.realmethod;
import java.io.Serializable;
import org.mockito.internal.creation.MockitoMethodProxy;
public interface HasCGLIBMethodProxy extends Serializable {
MockitoMethodProxy getMethodProxy();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation;
import org.mockito.cglib.proxy.MethodProxy;
public interface MockitoMethodProxy {
Object invokeSuper(Object target, Object[] arguments) throws Throwable;
MethodProxy getMethodProxy();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing;
import org.mockito.exceptions.Reporter;
import org.mockito.invocation.Invocation;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.DeprecatedOngoingStubbing;
import org.mockito.stubbing.OngoingStubbing;
import java.util.List;
public class OngoingStubbingImpl<T> extends BaseStubbing<T> {
private final InvocationContainerImpl invocationContainerImpl;
public OngoingStubbingImpl(InvocationContainerImpl invocationContainerImpl) {
this.invocationContainerImpl = invocationContainerImpl;
}
public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
if(!invocationContainerImpl.hasInvocationForPotentialStubbing()) {
new Reporter().incorrectUseOfApi();
}
invocationContainerImpl.addAnswer(answer);
return new ConsecutiveStubbing<T>(invocationContainerImpl);
}
public OngoingStubbing<T> then(Answer<?> answer) {
return thenAnswer(answer);
}
public DeprecatedOngoingStubbing<T> toAnswer(Answer<?> answer) {
invocationContainerImpl.addAnswer(answer);
return new ConsecutiveStubbing<T>(invocationContainerImpl);
}
public List<Invocation> getRegisteredInvocations() {
//TODO interface for tests
return invocationContainerImpl.getInvocations();
}
public <M> M getMock() {
return (M) invocationContainerImpl.invokedMock();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.answers;
import java.io.Serializable;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Optional Answer that adds partial mocking support
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* When this implementation is used, unstubbed methods will delegate to the real implementation.
* This is a way to create a partial mock object that calls real methods by default.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
*/
public class CallsRealMethods implements Answer<Object>, Serializable {
private static final long serialVersionUID = 9057165148930624087L;
public Object answer(InvocationOnMock invocation) throws Throwable {
return invocation.callRealMethod();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.listeners;
import org.mockito.exceptions.PrintableInvocation;
import org.mockito.invocation.DescribedInvocation;
/**
* Represent a method call on a mock.
*
* <p>
* Contains the information on the mock, the location of the stub
* the return value if it returned something (maybe null), or an
* exception if one was thrown when the method was invoked.
* </p>
*/
public interface MethodInvocationReport {
/**
* The return type is deprecated, please assign the return value from this method
* to the {@link DescribedInvocation} type. Sorry for inconvenience but we had to move
* {@link PrintableInvocation} to better place to keep the API consistency.
*
* @return Information on the method call, never {@code null}
*/
DescribedInvocation getInvocation();
/**
* @return The resulting value of the method invocation, may be <code>null</code>
*/
Object getReturnedValue();
/**
* @return The throwable raised by the method invocation, maybe <code>null</code>
*/
Throwable getThrowable();
/**
* @return <code>true</code> if an exception was raised, <code>false</code> otherwise
*/
boolean threwException();
/**
* @return Location of the stub invocation
*/
String getLocationOfStubbing();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.invocation.StubInfoImpl;
import org.mockito.internal.progress.MockingProgress;
import org.mockito.internal.stubbing.answers.AnswersValidator;
import org.mockito.internal.verification.DefaultRegisteredInvocations;
import org.mockito.internal.verification.RegisteredInvocations;
import org.mockito.internal.verification.SingleRegisteredInvocation;
import org.mockito.invocation.Invocation;
import org.mockito.mock.MockCreationSettings;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@SuppressWarnings("unchecked")
public class InvocationContainerImpl implements InvocationContainer, Serializable {
private static final long serialVersionUID = -5334301962749537177L;
private final LinkedList<StubbedInvocationMatcher> stubbed = new LinkedList<StubbedInvocationMatcher>();
private final MockingProgress mockingProgress;
private final List<Answer> answersForStubbing = new ArrayList<Answer>();
private final RegisteredInvocations registeredInvocations;
private InvocationMatcher invocationForStubbing;
public InvocationContainerImpl(MockingProgress mockingProgress, MockCreationSettings mockSettings) {
this.mockingProgress = mockingProgress;
this.registeredInvocations = createRegisteredInvocations(mockSettings);
}
public void setInvocationForPotentialStubbing(InvocationMatcher invocation) {
registeredInvocations.add(invocation.getInvocation());
this.invocationForStubbing = invocation;
}
public void resetInvocationForPotentialStubbing(InvocationMatcher invocationMatcher) {
this.invocationForStubbing = invocationMatcher;
}
public void addAnswer(Answer answer) {
registeredInvocations.removeLast();
addAnswer(answer, false);
}
public void addConsecutiveAnswer(Answer answer) {
addAnswer(answer, true);
}
public void addAnswer(Answer answer, boolean isConsecutive) {
Invocation invocation = invocationForStub
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>bing.getInvocation();
mockingProgress.stubbingCompleted(invocation);
AnswersValidator answersValidator = new AnswersValidator();
answersValidator.validate(answer, invocation);
synchronized (stubbed) {
if (isConsecutive) {
stubbed.getFirst().addAnswer(answer);
} else {
stubbed.addFirst(new StubbedInvocationMatcher(invocationForStubbing, answer));
}
}
}
Object answerTo(Invocation invocation) throws Throwable {
return findAnswerFor(invocation).answer(invocation);
}
public StubbedInvocationMatcher findAnswerFor(Invocation invocation) {
synchronized (stubbed) {
for (StubbedInvocationMatcher s : stubbed) {
if (s.matches(invocation)) {
s.markStubUsed(invocation);
invocation.markStubbed(new StubInfoImpl(s));
return s;
}
}
}
return null;
}
public void addAnswerForVoidMethod(Answer answer) {
answersForStubbing.add(answer);
}
public void setAnswersForStubbing(List<Answer> answers) {
answersForStubbing.addAll(answers);
}
public boolean hasAnswersForStubbing() {
return !answersForStubbing.isEmpty();
}
public boolean hasInvocationForPotentialStubbing() {
return !registeredInvocations.isEmpty();
}
public void setMethodForStubbing(InvocationMatcher invocation) {
invocationForStubbing = invocation;
assert hasAnswersForStubbing();
for (int i = 0; i < answersForStubbing.size(); i++) {
addAnswer(answersForStubbing.get(i), i != 0);
}
answersForStubbing.clear();
}
@Override
public String toString() {
return "invocationForStubbing: " + invocationForStubbing;
}
public List<Invocation> getInvocations() {
return registeredInvocations.getAll();
}
public List<StubbedInvocationMatcher> getStubbedInvocations() {
return stubbed;
}
public Object invokedMock() {
return invocationForStubbing.getInvocation().getMock();
}
public InvocationMatcher getInvocationForStubbing() {
return invocationForStubbing;
}
private RegisteredInvocations createRegisteredInvocations(MockCreationSettings mockSettings) {
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing;
import java.io.Serializable;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.invocation.DescribedInvocation;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@SuppressWarnings("unchecked")
public class StubbedInvocationMatcher extends InvocationMatcher implements Answer, Serializable {
private static final long serialVersionUID = 4919105134123672727L;
private final Queue<Answer> answers = new ConcurrentLinkedQueue<Answer>();
private DescribedInvocation usedAt;
public StubbedInvocationMatcher(InvocationMatcher invocation, Answer answer) {
super(invocation.getInvocation(), invocation.getMatchers());
this.answers.add(answer);
}
public Object answer(InvocationOnMock invocation) throws Throwable {
//see ThreadsShareGenerouslyStubbedMockTest
Answer a;
synchronized(answers) {
a = answers.size() == 1 ? answers.peek() : answers.poll();
}
return a.answer(invocation);
}
public void addAnswer(Answer answer) {
answers.add(answer);
}
public void markStubUsed(DescribedInvocation usedAt) {
this.usedAt = usedAt;
}
public boolean wasUsed() {
return usedAt != null;
}
@Override
public String toString() {
return super.toString() + " stubbed with: " + answers;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.defaultanswers;
import java.io.Serializable;
import org.mockito.configuration.IMockitoConfiguration;
import org.mockito.internal.configuration.GlobalConfiguration;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Globally configured Answer.
* <p>
* See javadoc for {@link IMockitoConfiguration}
*/
public class GloballyConfiguredAnswer implements Answer<Object>, Serializable {
private static final long serialVersionUID = 3585893470101750917L;
public Object answer(InvocationOnMock invocation) throws Throwable {
return new GlobalConfiguration().getDefaultAnswer().answer(invocation);
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>RETURNS_MOCKS
*/
RETURNS_MOCKS(new ReturnsMocks()),
/**
* An answer that returns <strong>deep stubs</strong> (not mocks).
*
* <p>Please see the {@link org.mockito.Mockito#RETURNS_DEEP_STUBS} documentation for more details.</p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
*/
RETURNS_DEEP_STUBS(new ReturnsDeepStubs()),
/**
* An answer that calls the real methods (used for partial mocks).
*
* <p>Please see the {@link org.mockito.Mockito#CALLS_REAL_METHODS} documentation for more details.</p>
*
* @see org.mockito.Mockito#CALLS_REAL_METHODS
*/
CALLS_REAL_METHODS(new CallsRealMethods())
;
private Answer<Object> implementation;
private Answers(Answer<Object> implementation) {
this.implementation = implementation;
}
public Answer<Object> get() {
return implementation;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.invocation;
import java.io.Serializable;
import java.lang.reflect.Method;
/**
* An invocation on a mock
* <p>
* A placeholder for mock, the method that was called and the arguments that were passed.
*/
public interface InvocationOnMock extends Serializable {
/**
* returns the mock object
*
* @return mock object
*/
Object getMock();
/**
* returns the method
*
* @return method
*/
Method getMethod();
/**
* returns arguments passed to the method
*
* @return arguments
*/
Object[] getArguments();
/**
* calls real method
* <p>
* <b>Warning:</b> depending on the real implementation it might throw exceptions
*
* @return whatever the real method returns / throws
* @throws Throwable in case real method throws
*/
Object callRealMethod() throws Throwable;
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.mockito.exceptions.base.MockitoException;
public class SerializableMethod implements Serializable, MockitoMethod {
private static final long serialVersionUID = 6005610965006048445L;
private Class<?> declaringClass;
private String methodName;
private Class<?>[] parameterTypes;
private Class<?> returnType;
private Class<?>[] exceptionTypes;
private boolean isVarArgs;
public SerializableMethod(Method method) {
declaringClass = method.getDeclaringClass();
methodName = method.getName();
parameterTypes = method.getParameterTypes();
returnType = method.getReturnType();
exceptionTypes = method.getExceptionTypes();
isVarArgs = method.isVarArgs();
}
public String getName() {
return methodName;
}
public Class<?> getReturnType() {
return returnType;
}
public Class<?>[] getParameterTypes() {
return parameterTypes;
}
public Class<?>[] getExceptionTypes() {
return exceptionTypes;
}
public boolean isVarArgs() {
return isVarArgs;
}
public Method getJavaMethod() {
try {
return declaringClass.getDeclaredMethod(methodName, parameterTypes);
} catch (SecurityException e) {
String message = String.format(
"The method %1$s.%2$s is probably private or protected and cannot be mocked.\n" +
"Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName);
throw new MockitoException(message, e);
} catch (NoSuchMethodException e) {
String message = String.format(
"The method %1$s.%2$s does not exists and you should not get to this point.\n" +
"Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName);
throw new MockitoException(message, e);
}
}
@Override
public int hashCode() {
return 1;
}
@Override
public boolean equals(Object obj
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal;
import java.util.Arrays;
import java.util.List;
import org.mockito.InOrder;
import org.mockito.MockSettings;
import org.mockito.MockingDetails;
import org.mockito.exceptions.Reporter;
import org.mockito.exceptions.misusing.NotAMockException;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.invocation.finder.VerifiableInvocationsFinder;
import org.mockito.internal.progress.IOngoingStubbing;
import org.mockito.internal.progress.MockingProgress;
import org.mockito.internal.progress.ThreadSafeMockingProgress;
import org.mockito.internal.stubbing.InvocationContainer;
import org.mockito.internal.stubbing.OngoingStubbingImpl;
import org.mockito.internal.stubbing.StubberImpl;
import org.mockito.internal.util.DefaultMockingDetails;
import org.mockito.internal.util.MockUtil;
import org.mockito.internal.verification.MockAwareVerificationMode;
import org.mockito.internal.verification.VerificationDataImpl;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.internal.verification.api.InOrderContext;
import org.mockito.internal.verification.api.VerificationDataInOrder;
import org.mockito.internal.verification.api.VerificationDataInOrderImpl;
import org.mockito.invocation.Invocation;
import org.mockito.mock.MockCreationSettings;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.DeprecatedOngoingStubbing;
import org.mockito.stubbing.OngoingStubbing;
import org.mockito.stubbing.Stubber;
import org.mockito.stubbing.VoidMethodStubbable;
import org.mockito.verification.VerificationMode;
@SuppressWarnings("unchecked")
public class MockitoCore {
private final Reporter reporter = new Reporter();
private final MockUtil mockUtil = new MockUtil();
private final MockingProgress mockingProgress = new ThreadSafeMockingProgress
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>();
public boolean isTypeMockable(Class<?> typeToMock) {
return mockUtil.isTypeMockable(typeToMock);
}
public <T> T mock(Class<T> typeToMock, MockSettings settings) {
if (!MockSettingsImpl.class.isInstance(settings)) {
throw new IllegalArgumentException(
"Unexpected implementation of '" + settings.getClass().getCanonicalName() + "'\n"
+ "At the moment, you cannot provide your own implementations that class.");
}
MockSettingsImpl impl = MockSettingsImpl.class.cast(settings);
MockCreationSettings<T> creationSettings = impl.confirm(typeToMock);
T mock = mockUtil.createMock(creationSettings);
mockingProgress.mockingStarted(mock, typeToMock);
return mock;
}
public IOngoingStubbing stub() {
IOngoingStubbing stubbing = mockingProgress.pullOngoingStubbing();
if (stubbing == null) {
mockingProgress.reset();
reporter.missingMethodInvocation();
}
return stubbing;
}
public <T> DeprecatedOngoingStubbing<T> stub(T methodCall) {
mockingProgress.stubbingStarted();
return (DeprecatedOngoingStubbing) stub();
}
public <T> OngoingStubbing<T> when(T methodCall) {
mockingProgress.stubbingStarted();
return (OngoingStubbing) stub();
}
public <T> T verify(T mock, VerificationMode mode) {
if (mock == null) {
reporter.nullPassedToVerify();
} else if (!mockUtil.isMock(mock)) {
reporter.notAMockPassedToVerify(mock.getClass());
}
mockingProgress.verificationStarted(new MockAwareVerificationMode(mock, mode));
return mock;
}
public <T> void reset(T ... mocks) {
mockingProgress.validateState();
mockingProgress.reset();
mockingProgress.resetOngoingStubbing();
for (T m : mocks) {
mockUtil.resetMock(m);
}
}
public void verifyNoMoreInteractions(Object... mocks) {
assertMocksNotEmpty(mocks);
mockingProgress.validateState();
for (Object mock : mocks
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>) {
try {
if (mock == null) {
reporter.nullPassedToVerifyNoMoreInteractions();
}
InvocationContainer invocations = mockUtil.getMockHandler(mock).getInvocationContainer();
VerificationDataImpl data = new VerificationDataImpl(invocations, null);
VerificationModeFactory.noMoreInteractions().verify(data);
} catch (NotAMockException e) {
reporter.notAMockPassedToVerifyNoMoreInteractions();
}
}
}
public void verifyNoMoreInteractionsInOrder(List<Object> mocks, InOrderContext inOrderContext) {
mockingProgress.validateState();
VerifiableInvocationsFinder finder = new VerifiableInvocationsFinder();
VerificationDataInOrder data = new VerificationDataInOrderImpl(inOrderContext, finder.find(mocks), null);
VerificationModeFactory.noMoreInteractions().verifyInOrder(data);
}
private void assertMocksNotEmpty(Object[] mocks) {
if (mocks == null || mocks.length == 0) {
reporter.mocksHaveToBePassedToVerifyNoMoreInteractions();
}
}
public InOrder inOrder(Object... mocks) {
if (mocks == null || mocks.length == 0) {
reporter.mocksHaveToBePassedWhenCreatingInOrder();
}
for (Object mock : mocks) {
if (mock == null) {
reporter.nullPassedWhenCreatingInOrder();
} else if (!mockUtil.isMock(mock)) {
reporter.notAMockPassedWhenCreatingInOrder();
}
}
return new InOrderImpl(Arrays.asList(mocks));
}
public Stubber doAnswer(Answer answer) {
mockingProgress.stubbingStarted();
mockingProgress.resetOngoingStubbing();
return new StubberImpl().doAnswer(answer);
}
public <T> VoidMethodStubbable<T> stubVoid(T mock) {
InternalMockHandler<T> handler = mockUtil.getMockHandler(mock);
mockingProgress.stubbingStarted();
return handler.voidMethodStubbable(mock);
}
public void validateMockitoUsage() {
mockingProgress.validateState();
}
/**
* For testing purposes only. Is not the part of main API.
* @return last invocation
*/
public Invocation getLastInvocation() {
Ongo
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>ingStubbingImpl ongoingStubbing = ((OngoingStubbingImpl) mockingProgress.pullOngoingStubbing());
List<Invocation> allInvocations = ongoingStubbing.getRegisteredInvocations();
return allInvocations.get(allInvocations.size()-1);
}
public Object[] ignoreStubs(Object... mocks) {
for (Object m : mocks) {
InvocationContainer invocationContainer = new MockUtil().getMockHandler(m).getInvocationContainer();
List<Invocation> ins = invocationContainer.getInvocations();
for (Invocation in : ins) {
if (in.stubInfo() != null) {
in.ignoreForVerification();
}
}
}
return mocks;
}
public MockingDetails mockingDetails(Object toInspect) {
return new DefaultMockingDetails(toInspect, new MockUtil());
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.configuration;
import org.mockito.ReturnValues;
import org.mockito.internal.configuration.InjectingAnnotationEngine;
import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
import org.mockito.stubbing.Answer;
/**
* DefaultConfiguration of Mockito framework
* <p>
* Currently it doesn't have many configuration options but it will probably change if future.
* <p>
* See javadocs for {@link IMockitoConfiguration} on info how to configure Mockito
*/
@SuppressWarnings("deprecation")//supressed until ReturnValues are removed
public class DefaultMockitoConfiguration implements IMockitoConfiguration {
/* (non-Javadoc)
* @see org.mockito.IMockitoConfiguration#getReturnValues()
*/
@Deprecated
public ReturnValues getReturnValues() {
throw new RuntimeException("\n" + "This method should not be used by the framework because it was deprecated"
+ "\n" + "Please report the failure to the Mockito mailing list");
}
public Answer<Object> getDefaultAnswer() {
return new ReturnsEmptyValues();
}
/* (non-Javadoc)
* @see org.mockito.IMockitoConfiguration#getAnnotationEngine()
*/
public AnnotationEngine getAnnotationEngine() {
return new InjectingAnnotationEngine();
}
/* (non-Javadoc)
* @see org.mockito.configuration.IMockitoConfiguration#cleansStackTrace()
*/
public boolean cleansStackTrace() {
return true;
}
/* (non-Javadoc)
* @see org.mockito.configuration.IMockitoConfiguration#enableClassCache()
*/
public boolean enableClassCache() {
return true;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.exceptions.stacktrace;
import org.mockito.exceptions.stacktrace.StackTraceCleaner;
import org.mockito.internal.configuration.ClassPathLoader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class StackTraceFilter implements Serializable {
static final long serialVersionUID = -5499819791513105700L;
private static StackTraceCleaner cleaner =
ClassPathLoader.getStackTraceCleanerProvider().getStackTraceCleaner(new DefaultStackTraceCleaner());
/**
* Example how the filter works (+/- means good/bad):
* [a+, b+, c-, d+, e+, f-, g+] -> [a+, b+, g+]
* Basically removes all bad from the middle. If any good are in the middle of bad those are also removed.
*/
public StackTraceElement[] filter(StackTraceElement[] target, boolean keepTop) {
//TODO: profile
List<StackTraceElement> unfilteredStackTrace = Arrays.asList(target);
int lastBad = -1;
int firstBad = -1;
for (int i = 0; i < unfilteredStackTrace.size(); i++) {
if (!cleaner.isOut(unfilteredStackTrace.get(i))) {
continue;
}
lastBad = i;
if (firstBad == -1) {
firstBad = i;
}
}
List<StackTraceElement> top;
if (keepTop && firstBad != -1) {
top = unfilteredStackTrace.subList(0, firstBad);
} else {
top = new LinkedList<StackTraceElement>();
}
List<StackTraceElement> bottom = unfilteredStackTrace.subList(lastBad + 1, unfilteredStackTrace.size());
List<StackTraceElement> filtered = new ArrayList<StackTraceElement>(top);
filtered.addAll(bottom);
return filtered.toArray(new StackTraceElement[]{});
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.defaultanswers;
import java.io.Serializable;
import java.lang.reflect.Array;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* It's likely this implementation will be used by default by every Mockito 2.0 mock.
* <p>
* Currently <b>used only</b> by {@link Mockito#RETURNS_SMART_NULLS}
* <p>
* Current version of Mockito mocks by deafult use {@link ReturnsEmptyValues}
* <ul>
* <li>
* Returns appropriate primitive for primitive-returning methods
* </li>
* <li>
* Returns consistent values for primitive wrapper classes (e.g. int-returning method retuns 0 <b>and</b> Integer-returning method returns 0, too)
* </li>
* <li>
* Returns empty collection for collection-returning methods (works for most commonly used collection types)
* </li>
* <li>
* Returns empty array for array-returning methods
* </li>
* <li>
* Returns "" for String-returning method
* </li>
* <li>
* Returns description of mock for toString() method
* </li>
* <li>
* Returns non-zero for Comparable#compareTo(T other) method (see issue 184)
* </li>
* <li>
* Returns null for everything else
* </li>
* </ul>
*/
public class ReturnsMoreEmptyValues implements Answer<Object>, Serializable {
private static final long serialVersionUID = -2816745041482698471L;
private Answer<Object> delegate = new ReturnsEmptyValues();
/* (non-Javadoc)
* @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
*/
public Object answer(InvocationOnMock invocation) throws Throwable {
Object ret
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> = delegate.answer(invocation);
if (ret != null) {
return ret;
}
Class<?> returnType = invocation.getMethod().getReturnType();
return returnValueFor(returnType);
}
Object returnValueFor(Class<?> type) {
if (type == String.class) {
return "";
} else if (type.isArray()) {
Class<?> componenetType = type.getComponentType();
return Array.newInstance(componenetType, 0);
}
return null;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.defaultanswers;
import java.io.Serializable;
import java.lang.reflect.Modifier;
import org.mockito.Mockito;
import org.mockito.exceptions.Reporter;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.invocation.Location;
import org.mockito.internal.util.ObjectMethodsGuru;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Optional Answer that can be used with
* {@link Mockito#mock(Class, Answer)}
* <p>
* This implementation can be helpful when working with legacy code. Unstubbed
* methods often return null. If your code uses the object returned by an
* unstubbed call you get a NullPointerException. This implementation of
* Answer returns SmartNulls instead of nulls.
* SmartNull gives nicer exception message than NPE because it points out the
* line where unstubbed method was called. You just click on the stack trace.
* <p>
* ReturnsSmartNulls first tries to return ordinary return values (see
* {@link ReturnsMoreEmptyValues}) then it tries to return SmartNull. If the
* return type is not mockable (e.g. final) then ordinary null is returned.
* <p>
* ReturnsSmartNulls will be probably the default return values strategy in
* Mockito 2.0
*/
public class ReturnsSmartNulls implements Answer<Object>, Serializable {
private static final long serialVersionUID = 7618312406617949441L;
private final Answer<Object> delegate = new ReturnsMoreEmptyValues();
public Object answer(final InvocationOnMock invocation) throws Throwable {
Object defaultReturnValue = delegate.answer(invocation);
if (defaultReturnValue != null) {
return defaultReturnValue;
}
Class<?> type = invocation.getMethod().getReturnType();
if (!type.isPrimitive() && !Modifier.isFinal(type.getModifiers())) {
final Location location = new LocationImpl();
return Mockito.mock(type, new ThrowsSmartNullPointer(invocation
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>, location));
}
return null;
}
private static class ThrowsSmartNullPointer implements Answer {
private final InvocationOnMock unstubbedInvocation;
private final Location location;
public ThrowsSmartNullPointer(InvocationOnMock unstubbedInvocation, Location location) {
this.unstubbedInvocation = unstubbedInvocation;
this.location = location;
}
public Object answer(InvocationOnMock currentInvocation) throws Throwable {
if (new ObjectMethodsGuru().isToString(currentInvocation.getMethod())) {
return "SmartNull returned by this unstubbed method call on a mock:\n" +
unstubbedInvocation.toString();
}
new Reporter().smartNullPointerException(unstubbedInvocation.toString(), location);
return null;
}
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation;
public abstract class AbstractMockitoMethodProxy implements MockitoMethodProxy {
public Object invokeSuper(Object target, Object[] arguments) throws Throwable {
return getMethodProxy().invokeSuper(target, arguments);
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation;
import org.mockito.invocation.DescribedInvocation;
import org.mockito.invocation.Location;
import org.mockito.invocation.StubInfo;
import java.io.Serializable;
public class StubInfoImpl implements StubInfo, Serializable {
private static final long serialVersionUID = 2125827349332068867L;
private DescribedInvocation stubbedAt;
public StubInfoImpl(DescribedInvocation stubbedAt) {
this.stubbedAt = stubbedAt;
}
public Location stubbedAt() {
return stubbedAt.getLocation();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.defaultanswers;
import org.mockito.internal.util.MockUtil;
import org.mockito.internal.util.ObjectMethodsGuru;
import org.mockito.internal.util.Primitives;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.mock.MockName;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Default answer of every Mockito mock.
* <ul>
* <li>
* Returns appropriate primitive for primitive-returning methods
* </li>
* <li>
* Returns consistent values for primitive wrapper classes (e.g. int-returning method retuns 0 <b>and</b> Integer-returning method returns 0, too)
* </li>
* <li>
* Returns empty collection for collection-returning methods (works for most commonly used collection types)
* </li>
* <li>
* Returns description of mock for toString() method
* </li>
* <li>
* Returns zero if references are equals otherwise non-zero for Comparable#compareTo(T other) method (see issue 184)
* </li>
* <li>
* Returns null for everything else
* </li>
* </ul>
*/
public class ReturnsEmptyValues implements Answer<Object>, Serializable {
private static final long serialVersionUID = 1998191268711234347L;
ObjectMethodsGuru methodsGuru = new ObjectMethodsGuru();
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> MockUtil mockUtil = new MockUtil();
/* (non-Javadoc)
* @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
*/
public Object answer(InvocationOnMock invocation) {
if (methodsGuru.isToString(invocation.getMethod())) {
Object mock = invocation.getMock();
MockName name = mockUtil.getMockName(mock);
if (name.isDefault()) {
return "Mock for " + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode();
} else {
return name.toString();
}
} else if (methodsGuru.isCompareToMethod(invocation.getMethod())) {
//see issue 184.
//mocks by default should return 0 if references are the same, otherwise some other value because they are not the same. Hence we return 1 (anything but 0 is good).
//Only for compareTo() method by the Comparable interface
return invocation.getMock() == invocation.getArguments()[0] ? 0 : 1;
}
Class<?> returnType = invocation.getMethod().getReturnType();
return returnValueFor(returnType);
}
Object returnValueFor(Class<?> type) {
if (Primitives.isPrimitiveOrWrapper(type)) {
return Primitives.defaultValueForPrimitiveOrWrapper(type);
//new instances are used instead of Collections.emptyList(), etc.
//to avoid UnsupportedOperationException if code under test modifies returned collection
} else if (type == Collection.class) {
return new LinkedList<Object>();
} else if (type == Set.class) {
return new HashSet<Object>();
} else if (type == HashSet.class) {
return new HashSet<Object>();
} else if (type == SortedSet.class) {
return new TreeSet<Object>();
} else if (type == TreeSet.class) {
return new TreeSet<Object>();
} else if (type == LinkedHashSet.class) {
return new LinkedHashSet<Object>();
} else if (type == List.class) {
return new LinkedList<Object>();
} else if (type == LinkedList.class) {
return new LinkedList<Object>();
} else if (type == ArrayList.class) {
return new ArrayList<Object>();
} else if (
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>type == Map.class) {
return new HashMap<Object, Object>();
} else if (type == HashMap.class) {
return new HashMap<Object, Object>();
} else if (type == SortedMap.class) {
return new TreeMap<Object, Object>();
} else if (type == TreeMap.class) {
return new TreeMap<Object, Object>();
} else if (type == LinkedHashMap.class) {
return new LinkedHashMap<Object, Object>();
}
// TODO return empty Iterable ; see issue 175
//Let's not care about the rest of collections.
return null;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation;
import org.hamcrest.Matcher;
import org.mockito.internal.matchers.CapturesArguments;
import org.mockito.internal.matchers.MatcherDecorator;
import org.mockito.internal.matchers.VarargMatcher;
import org.mockito.internal.reporting.PrintSettings;
import org.mockito.invocation.DescribedInvocation;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.Location;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
@SuppressWarnings("unchecked")
public class InvocationMatcher implements DescribedInvocation, CapturesArgumensFromInvocation, Serializable {
private static final long serialVersionUID = -3047126096857467610L;
private final Invocation invocation;
private final List<Matcher> matchers;
public InvocationMatcher(Invocation invocation, List<Matcher> matchers) {
this.invocation = invocation;
if (matchers.isEmpty()) {
this.matchers = ArgumentsProcessor.argumentsToMatchers(invocation.getArguments());
} else {
this.matchers = matchers;
}
}
public InvocationMatcher(Invocation invocation) {
this(invocation, Collections.<Matcher>emptyList());
}
public Method getMethod() {
return invocation.getMethod();
}
public Invocation getInvocation() {
return this.invocation;
}
public List<Matcher> getMatchers() {
return this.matchers;
}
public String toString() {
return new PrintSettings().print(matchers, invocation);
}
public boolean matches(Invocation actual) {
return invocation.getMock().equals(actual.getMock())
&& hasSameMethod(actual)
&& new ArgumentsComparator().argumentsMatch(this, actual);
}
private boolean safelyArgumentsMatch(Object[] actualArgs) {
try {
return new ArgumentsComparator().argumentsMatch(this, actualArgs);
} catch (Throwable t) {
return false;
}
}
/**
* similar means the
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> same method name, same mock, unverified
* and: if arguments are the same cannot be overloaded
*/
public boolean hasSimilarMethod(Invocation candidate) {
String wantedMethodName = getMethod().getName();
String currentMethodName = candidate.getMethod().getName();
final boolean methodNameEquals = wantedMethodName.equals(currentMethodName);
final boolean isUnverified = !candidate.isVerified();
final boolean mockIsTheSame = getInvocation().getMock() == candidate.getMock();
final boolean methodEquals = hasSameMethod(candidate);
if (!methodNameEquals || !isUnverified || !mockIsTheSame) {
return false;
}
final boolean overloadedButSameArgs = !methodEquals && safelyArgumentsMatch(candidate.getArguments());
return !overloadedButSameArgs;
}
public boolean hasSameMethod(Invocation candidate) {
//not using method.equals() for 1 good reason:
//sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest
Method m1 = invocation.getMethod();
Method m2 = candidate.getMethod();
if (m1.getName() != null && m1.getName().equals(m2.getName())) {
/* Avoid unnecessary cloning */
Class[] params1 = m1.getParameterTypes();
Class[] params2 = m2.getParameterTypes();
if (params1.length == params2.length) {
for (int i = 0; i < params1.length; i++) {
if (params1[i] != params2[i])
return false;
}
return true;
}
}
return false;
}
public Location getLocation() {
return invocation.getLocation();
}
public void captureArgumentsFrom(Invocation invocation) {
for (int position = 0; position < matchers.size(); position++) {
Matcher m = matchers.get(position);
if (m instanceof CapturesArguments && invocation.getRawArguments().length > position) {
//TODO SF - this whole lot can be moved captureFrom implementation
if(isVariableArgument(invocation, position) && isVarargMatcher(m)) {
Object array = invocation.getRawArguments()[position];
for (int i = 0; i < Array.getLength(array); i++) {
((Captures
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.answers;
import java.io.Serializable;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class Returns implements Answer<Object>, Serializable {
private static final long serialVersionUID = -6245608253574215396L;
private final Object value;
public Returns(Object value) {
this.value = value;
}
public Object answer(InvocationOnMock invocation) throws Throwable {
return value;
}
public String printReturnType() {
return value.getClass().getSimpleName();
}
public Class<?> getReturnType() {
return value.getClass();
}
public boolean returnsNull() {
return value == null;
}
@Override
public String toString() {
return "Returns: " + value;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.stubbing;
import org.mockito.invocation.InvocationOnMock;
/**
* Generic interface to be used for configuring mock's answer.
* Answer specifies an action that is executed and a return value that is returned when you interact with the mock.
* <p>
* Example of stubbing a mock with custom answer:
*
* <pre class="code"><code class="java">
* when(mock.someMethod(anyString())).thenAnswer(new Answer() {
* Object answer(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Object mock = invocation.getMock();
* return "called with arguments: " + Arrays.toString(args);
* }
* });
*
* //Following prints "called with arguments: [foo]"
* System.out.println(mock.someMethod("foo"));
* </code></pre>
*
* @param <T> the type to return.
*/
public interface Answer<T> {
/**
* @param invocation the invocation on the mock.
*
* @return the value to be returned
*
* @throws Throwable the throwable to be thrown
*/
T answer(InvocationOnMock invocation) throws Throwable;
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation.realmethod;
public interface RealMethod {
Object invoke(Object target, Object[] arguments) throws Throwable;
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.verification;
import org.mockito.invocation.Invocation;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
public class SingleRegisteredInvocation implements RegisteredInvocations, Serializable {
private Invocation invocation;
public void add(Invocation invocation) {
this.invocation = invocation;
}
public void removeLast() {
invocation = null;
}
public List<Invocation> getAll() {
return Collections.emptyList();
}
public boolean isEmpty() {
return invocation == null;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>p>
* See javadoc {@link ReturnValues} for info why this method was deprecated
* <p>
* Allows configuring the default return values of unstubbed invocations
* <p>
* See javadoc for {@link IMockitoConfiguration}
*/
@Deprecated
ReturnValues getReturnValues();
/**
* Allows configuring the default answers of unstubbed invocations
* <p>
* See javadoc for {@link IMockitoConfiguration}
*/
Answer<Object> getDefaultAnswer();
/**
* Configures annotations for mocks
* <p>
* See javadoc for {@link IMockitoConfiguration}
*/
AnnotationEngine getAnnotationEngine();
/**
* This should be turned on unless you're a Mockito developer and you wish
* to have verbose (read: messy) stack traces that only few understand (eg:
* Mockito developers)
* <p>
* See javadoc for {@link IMockitoConfiguration}
*
* @return if Mockito should clean stack traces
*/
boolean cleansStackTrace();
/**
* Allow objenesis to cache classes. If you're in an environment where classes
* are dynamically reloaded, you can disable this to avoid classcast exceptions.
*/
boolean enableClassCache();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.configuration;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import org.mockito.Mockito;
import org.mockito.internal.configuration.InjectingAnnotationEngine;
import org.mockito.stubbing.Answer;
import org.mockitousage.configuration.SmartMock;
public class MockitoConfiguration extends DefaultMockitoConfiguration implements IMockitoConfiguration {
private Answer<Object> overriddenDefaultAnswer = null;
private boolean cleansStackTrace;
private AnnotationEngine overriddenEngine;
private boolean enableClassCache = true;
//for testing purposes, allow to override the configuration
public void overrideDefaultAnswer(Answer<Object> defaultAnswer) {
this.overriddenDefaultAnswer = defaultAnswer;
}
//for testing purposes, allow to override the configuration
public void overrideCleansStackTrace(boolean cleansStackTrace) {
this.cleansStackTrace = cleansStackTrace;
}
//for testing purposes, allow to override the annotation engine
public void overrideAnnotationEngine(AnnotationEngine engine) {
this.overriddenEngine = engine;
}
//for testing purposes, allow to override the annotation engine
public void overrideEnableClassCache(boolean enableClassCache) {
this.enableClassCache = enableClassCache;
}
@Override
public Answer<Object> getDefaultAnswer() {
if (overriddenDefaultAnswer == null) {
return super.getDefaultAnswer();
} else {
return overriddenDefaultAnswer;
}
}
@Override
public AnnotationEngine getAnnotationEngine() {
if (this.overriddenEngine != null) {
return this.overriddenEngine;
}
return new InjectingAnnotationEngine() {
@Override
public Object createMockFor(Annotation annotation, Field field) {
if (annotation instanceof SmartMock) {
return Mockito.mock(field.getType(), Mockito.RETURNS_SMART_NULLS);
} else {
return super.createMockFor(annotation, field);
}
}
};
}
@Override
public boolean cleansStackTrace() {
return cleansStackTrace;
}
@Override
public boolean enableClassCache() {
return enableClassCache;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>
* <li>second time foo(10) is called the mock will throw RuntimeException</li>
* <li>every consecutive time foo(10) is called the mock will throw RuntimeException</li>
* </ul>
* <p>
* See examples in javadoc for {@link Mockito#stubVoid}
*
* @return VoidMethodStubbable - typically to choose void method and finish stubbing
*/
VoidMethodStubbable<T> toReturn();
/**
* Stubs a void method with generic {@link Answer}
* <p>
* For Example:
* <pre class="code"><code class="java">
* stubVoid(mock)
* .toAnswer(new Answer() {
* public Object answer(InvocationOnMOck invocation) {
* Visitor v = (Visitor) invocation.getArguments()[0];
* v.visitMock(invocation.getMock());
*
* return null;
* }
* })
* .on().accept(any());
* </code></pre>
*
* @param answer the custom answer to execute.
*
* @return VoidMethodStubbable - typically to choose void method and finish stubbing
*/
VoidMethodStubbable<T> toAnswer(Answer<?> answer);
/**
* Choose void method for stubbing. E.g:
*
* <pre class="code"><code class="java">
* stubVoid(mock).toThrow(new RuntimeException()).on().someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito#stubVoid}
*
* @return mock object itself
*/
T on();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.configuration;
import org.mockito.ReturnValues;
import org.mockito.configuration.AnnotationEngine;
import org.mockito.configuration.DefaultMockitoConfiguration;
import org.mockito.configuration.IMockitoConfiguration;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
/**
* Thread-safe wrapper on user-defined org.mockito.configuration.MockitoConfiguration implementation
*/
@SuppressWarnings("deprecation")//supressed until ReturnValues are removed
public class GlobalConfiguration implements IMockitoConfiguration, Serializable {
static final long serialVersionUID = -2860353062105505938L;
private static ThreadLocal<IMockitoConfiguration> globalConfiguration = new ThreadLocal<IMockitoConfiguration>();
//back door for testing
IMockitoConfiguration getIt() {
return globalConfiguration.get();
}
public GlobalConfiguration() {
//Configuration should be loaded only once but I cannot really test it
if (globalConfiguration.get() == null) {
globalConfiguration.set(createConfig());
}
}
private IMockitoConfiguration createConfig() {
IMockitoConfiguration defaultConfiguration = new DefaultMockitoConfiguration();
IMockitoConfiguration config = new ClassPathLoader().loadConfiguration();
if (config != null) {
return config;
} else {
return defaultConfiguration;
}
}
public static void validate() {
new GlobalConfiguration();
}
public ReturnValues getReturnValues() {
return globalConfiguration.get().getReturnValues();
}
public AnnotationEngine getAnnotationEngine() {
return globalConfiguration.get().getAnnotationEngine();
}
public boolean cleansStackTrace() {
return globalConfiguration.get().cleansStackTrace();
}
public boolean enableClassCache() {
return globalConfiguration.get().enableClassCache();
}
public Answer<Object> getDefaultAnswer() {
return globalConfiguration.get().getDefaultAnswer();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation;
import java.io.Serializable;
import org.mockito.cglib.proxy.MethodProxy;
import org.mockito.internal.util.reflection.Whitebox;
public class SerializableMockitoMethodProxy extends AbstractMockitoMethodProxy implements Serializable {
private static final long serialVersionUID = -5337859962876770632L;
private final Class<?> c1;
private final Class<?> c2;
private final String desc;
private final String name;
private final String superName;
private transient MethodProxy methodProxy;
public SerializableMockitoMethodProxy(MethodProxy methodProxy) {
Object info = Whitebox.getInternalState(methodProxy, "createInfo");
c1 = (Class<?>) Whitebox.getInternalState(info, "c1");
c2 = (Class<?>) Whitebox.getInternalState(info, "c2");
desc = methodProxy.getSignature().getDescriptor();
name = methodProxy.getSignature().getName();
superName = methodProxy.getSuperName();
this.methodProxy = methodProxy;
}
public MethodProxy getMethodProxy() {
if (methodProxy == null)
methodProxy = MethodProxy.create(c1, c2, desc, name, superName);
return methodProxy;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> new LocationImpl(),
""
));
}
private Object locationsOf(Collection<LocalizedMatcher> matchers) {
List<String> description = new ArrayList<String>();
for (LocalizedMatcher matcher : matchers)
description.add(matcher.getLocation().toString());
return join(description.toArray());
}
public void argumentsAreDifferent(String wanted, String actual, Location actualLocation) {
String message = join("Argument(s) are different! Wanted:",
wanted,
new LocationImpl(),
"Actual invocation has different arguments:",
actual,
actualLocation,
""
);
if (JUnitTool.hasJUnit()) {
throw JUnitTool.createArgumentsAreDifferentException(message, wanted, actual);
} else {
throw new ArgumentsAreDifferent(message);
}
}
public void wantedButNotInvoked(DescribedInvocation wanted) {
throw new WantedButNotInvoked(createWantedButNotInvokedMessage(wanted));
}
public void wantedButNotInvoked(DescribedInvocation wanted, List<? extends DescribedInvocation> invocations) {
String allInvocations;
if (invocations.isEmpty()) {
allInvocations = "Actually, there were zero interactions with this mock.\n";
} else {
StringBuilder sb = new StringBuilder("\nHowever, there were other interactions with this mock:\n");
for (DescribedInvocation i : invocations) {
sb.append(i.toString())
.append("\n")
.append(i.getLocation())
.append("\n\n");
}
allInvocations = sb.toString();
}
String message = createWantedButNotInvokedMessage(wanted);
throw new WantedButNotInvoked(message + allInvocations);
}
private String createWantedButNotInvokedMessage(DescribedInvocation wanted) {
return join(
"Wanted but not invoked:",
wanted.toString(),
new LocationImpl(),
""
);
}
public void wantedButNotInvokedInOrder(DescribedInvocation wanted, DescribedInvocation previous) {
throw new VerificationInOrderFailure(join(
"Verification in order failure",
"Wanted but not invoked:",
wanted.toString(),
new LocationImpl(),
"Wanted anywhere AFTER following interaction:",
previous.toString(),
previous.getLocation(),
""
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>verified: final/private/equals()/hashCode().",
""
));
}
public void smartNullPointerException(String invocation, Location location) {
throw new SmartNullPointerException(join(
"You have a NullPointerException here:",
new LocationImpl(),
"because this method call was *not* stubbed correctly:",
location,
invocation,
""
));
}
public void noArgumentValueWasCaptured() {
throw new MockitoException(join(
"No argument value was captured!",
"You might have forgotten to use argument.capture() in verify()...",
"...or you used capture() in stubbing but stubbed method was not called.",
"Be aware that it is recommended to use capture() only with verify()",
"",
"Examples of correct argument capturing:",
" ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);",
" verify(mock).doSomething(argument.capture());",
" assertEquals(\"John\", argument.getValue().getName());",
""
));
}
public void extraInterfacesDoesNotAcceptNullParameters() {
throw new MockitoException(join(
"extraInterfaces() does not accept null parameters."
));
}
public void extraInterfacesAcceptsOnlyInterfaces(Class<?> wrongType) {
throw new MockitoException(join(
"extraInterfaces() accepts only interfaces.",
"You passed following type: " + wrongType.getSimpleName() + " which is not an interface."
));
}
public void extraInterfacesCannotContainMockedType(Class<?> wrongType) {
throw new MockitoException(join(
"extraInterfaces() does not accept the same type as the mocked type.",
"You mocked following type: " + wrongType.getSimpleName(),
"and you passed the same very interface to the extraInterfaces()"
));
}
public void extraInterfacesRequiresAtLeastOneInterface() {
throw new MockitoException(join(
"extraInterfaces() requires at least one interface."
));
}
public void mockedTypeIsInconsistentWithSpiedInstanceType(Class<?> mockedType, Object spiedInstance) {
throw new MockitoException(join(
"Mocked type must be the same as the type of your spied instance.",
"Mocked type must be: " + spiedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(),
" //correct spying
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>The invocation listener with type " + listener.getClass().getName(),
"threw an exception : " + listenerThrowable.getClass().getName() + listenerThrowable.getMessage()), listenerThrowable);
}
public void cannotInjectDependency(Field field, Object matchingMock, Exception details) {
throw new MockitoException(join(
"Mockito couldn't inject mock dependency '" + new MockUtil().getMockName(matchingMock) + "' on field ",
"'" + field + "'",
"whose type '" + field.getDeclaringClass().getCanonicalName() + "' was annotated by @InjectMocks in your test.",
"Also I failed because: " + details.getCause().getMessage(),
""
), details);
}
public void mockedTypeIsInconsistentWithDelegatedInstanceType(Class mockedType, Object delegatedInstance) {
throw new MockitoException(join(
"Mocked type must be the same as the type of your delegated instance.",
"Mocked type must be: " + delegatedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(),
" //correct delegate:",
" spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new ArrayList()<- );",
" //incorrect - types don't match:",
" spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new HashSet()<- );"
));
}
public void spyAndDelegateAreMutuallyExclusive() {
throw new MockitoException(join(
"Settings should not define a spy instance and a delegated instance at the same time."
)) ;
}
public void invalidArgumentRangeAtIdentityAnswerCreationTime() {
throw new MockitoException(join("Invalid argument index.",
"The index need to be a positive number that indicates the position of the argument to return.",
"However it is possible to use the -1 value to indicates that the last argument should be",
"returned."));
}
public int invalidArgumentPositionRangeAtInvocationTime(InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) {
throw new MockitoException(
join("Invalid argument index for the current invocation of method : ",
" -> " + new MockUtil().getMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
"",
(willReturnLastParameter ?
"Last parameter wanted
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> *
* @param throwable to be thrown on method invocation
*
* @return iOngoingStubbing object that allows stubbing consecutive calls
*/
DeprecatedOngoingStubbing<T> toThrow(Throwable throwable);
/**
* Set a generic Answer for the stubbed method. E.g:
* <pre class="code"><code class="java">
* stub(mock.someMethod(10)).toAnswer(new Answer<Integer>() {
* public Integer answer(InvocationOnMock invocation) throws Throwable {
* return (Integer) invocation.getArguments()[0];
* }
* }
* </code></pre>
*
* @param answer the custom answer to execute.
*
* @return iOngoingStubbing object that allows stubbing consecutive calls
*/
DeprecatedOngoingStubbing<T> toAnswer(Answer<?> answer);
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util;
/**
* Pre-made preconditions
*/
public class Checks {
public static <T> T checkNotNull(T value, String checkedValue) {
if(value == null) {
throw new NullPointerException(checkedValue + " should not be null");
}
return value;
}
public static <T extends Iterable> T checkItemsNotNull(T iterable, String checkedIterable) {
checkNotNull(iterable, checkedIterable);
for (Object item : iterable) {
checkNotNull(item, "item in " + checkedIterable);
}
return iterable;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation.realmethod;
import java.io.Serializable;
import org.mockito.internal.creation.MockitoMethodProxy;
public class CGLIBProxyRealMethod implements RealMethod, HasCGLIBMethodProxy, Serializable {
private static final long serialVersionUID = -4596470901191501582L;
private final MockitoMethodProxy methodProxy;
public CGLIBProxyRealMethod(MockitoMethodProxy methodProxy) {
this.methodProxy = methodProxy;
}
public Object invoke(Object target, Object[] arguments) throws Throwable {
return methodProxy.invokeSuper(target, arguments);
}
public MockitoMethodProxy getMethodProxy() {
return methodProxy;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation.settings;
import org.mockito.listeners.InvocationListener;
import org.mockito.mock.MockCreationSettings;
import org.mockito.mock.MockName;
import org.mockito.mock.SerializableMode;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* by Szczepan Faber, created at: 4/9/12
*/
public class CreationSettings<T> implements MockCreationSettings<T>, Serializable {
private static final long serialVersionUID = -6789800638070123629L;
protected Class<T> typeToMock;
protected Set<Class> extraInterfaces = new LinkedHashSet<Class>();
protected String name;
protected Object spiedInstance;
protected Answer<Object> defaultAnswer;
protected MockName mockName;
protected SerializableMode serializableMode = SerializableMode.NONE;
protected List<InvocationListener> invocationListeners = new ArrayList<InvocationListener>();
protected boolean stubOnly;
public CreationSettings() {}
@SuppressWarnings("unchecked")
public CreationSettings(CreationSettings copy) {
this.typeToMock = copy.typeToMock;
this.extraInterfaces = copy.extraInterfaces;
this.name = copy.name;
this.spiedInstance = copy.spiedInstance;
this.defaultAnswer = copy.defaultAnswer;
this.mockName = copy.mockName;
this.serializableMode = copy.serializableMode;
this.invocationListeners = copy.invocationListeners;
this.stubOnly = copy.stubOnly;
}
public Class<T> getTypeToMock() {
return typeToMock;
}
public CreationSettings<T> setTypeToMock(Class<T> typeToMock) {
this.typeToMock = typeToMock;
return this;
}
public Set<Class> getExtraInterfaces() {
return extraInterfaces;
}
public CreationSettings<T> set
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>ExtraInterfaces(Set<Class> extraInterfaces) {
this.extraInterfaces = extraInterfaces;
return this;
}
public String getName() {
return name;
}
public Object getSpiedInstance() {
return spiedInstance;
}
public Answer<Object> getDefaultAnswer() {
return defaultAnswer;
}
public MockName getMockName() {
return mockName;
}
public CreationSettings<T> setMockName(MockName mockName) {
this.mockName = mockName;
return this;
}
public boolean isSerializable() {
return serializableMode != SerializableMode.NONE;
}
public SerializableMode getSerializableMode() {
return serializableMode;
}
public List<InvocationListener> getInvocationListeners() {
return invocationListeners;
}
public boolean isStubOnly() {
return stubOnly;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.configuration;
import org.mockito.MockitoAnnotations;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* Configures mock creation logic behind @Mock, @Captor and @Spy annotations
* <p>
* If you are interested then see implementations or source code of {@link MockitoAnnotations#initMocks(Object)}
*/
public interface AnnotationEngine {
/**
* @deprecated
* Please use {@link AnnotationEngine#process(Class, Object)} method instead that is more robust
* <p>
* Creates mock, ArgumentCaptor or wraps field instance in spy object.
* Only if of correct annotation type.
*
* @param annotation Annotation
* @param field Field details
*/
@Deprecated
Object createMockFor(Annotation annotation, Field field);
/**
* Allows extending the interface to perform action on specific fields on the test class.
* <p>
* See the implementation of this method to figure out what is it for.
*
* @param clazz Class where to extract field information, check implementation for details
* @param testInstance Test instance
*/
void process(Class<?> clazz, Object testInstance);
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.DeprecatedOngoingStubbing;
import org.mockito.stubbing.OngoingStubbing;
public class ConsecutiveStubbing<T> extends BaseStubbing<T> {
private final InvocationContainerImpl invocationContainerImpl;
public ConsecutiveStubbing(InvocationContainerImpl invocationContainerImpl) {
this.invocationContainerImpl = invocationContainerImpl;
}
public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
invocationContainerImpl.addConsecutiveAnswer(answer);
return this;
}
public OngoingStubbing<T> then(Answer<?> answer) {
return thenAnswer(answer);
}
public DeprecatedOngoingStubbing<T> toAnswer(Answer<?> answer) {
invocationContainerImpl.addConsecutiveAnswer(answer);
return this;
}
public <M> M getMock() {
return (M) invocationContainerImpl.invokedMock();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util;
import java.lang.reflect.Modifier;
import org.mockito.exceptions.misusing.NotAMockException;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.configuration.ClassPathLoader;
import org.mockito.internal.creation.settings.CreationSettings;
import org.mockito.internal.handler.MockHandlerFactory;
import org.mockito.internal.util.reflection.LenientCopyTool;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
import org.mockito.mock.MockName;
import org.mockito.plugins.MockMaker;
@SuppressWarnings("unchecked")
public class MockUtil {
private static final MockMaker mockMaker = ClassPathLoader.getMockMaker();
public boolean isTypeMockable(Class<?> type) {
return !type.isPrimitive() && !Modifier.isFinal(type.getModifiers());
}
public <T> T createMock(MockCreationSettings<T> settings) {
MockHandler mockHandler = new MockHandlerFactory().create(settings);
T mock = mockMaker.createMock(settings, mockHandler);
Object spiedInstance = settings.getSpiedInstance();
if (spiedInstance != null) {
new LenientCopyTool().copyToMock(spiedInstance, mock);
}
return mock;
}
public <T> void resetMock(T mock) {
InternalMockHandler oldHandler = (InternalMockHandler) getMockHandler(mock);
MockCreationSettings settings = oldHandler.getMockSettings();
MockHandler newHandler = new MockHandlerFactory().create(settings);
mockMaker.resetMock(mock, newHandler, settings);
}
public <T> InternalMockHandler<T> getMockHandler(T mock) {
if (mock == null) {
throw new NotAMockException("Argument should be a mock, but is null!");
}
if (isMockitoMock(mock)) {
MockHandler handler = mockMaker.getHandler(mock);
return (InternalMockHandler) handler;
} else {
throw new NotAMockException("Argument should
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> be a mock, but is: " + mock.getClass());
}
}
public boolean isMock(Object mock) {
// double check to avoid classes that have the same interfaces, could be great to have a custom mockito field in the proxy instead of relying on instance fields
return isMockitoMock(mock);
}
public boolean isSpy(Object mock) {
return isMockitoMock(mock) && getMockSettings(mock).getSpiedInstance() != null;
}
private <T> boolean isMockitoMock(T mock) {
return mockMaker.getHandler(mock) != null;
}
public MockName getMockName(Object mock) {
return getMockHandler(mock).getMockSettings().getMockName();
}
public void maybeRedefineMockName(Object mock, String newName) {
MockName mockName = getMockName(mock);
//TODO SF hacky...
if (mockName.isDefault() && getMockHandler(mock).getMockSettings() instanceof CreationSettings) {
((CreationSettings) getMockHandler(mock).getMockSettings()).setMockName(new MockNameImpl(newName));
}
}
public MockCreationSettings getMockSettings(Object mock) {
return getMockHandler(mock).getMockSettings();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.progress;
import java.io.Serializable;
import org.mockito.MockSettings;
import org.mockito.internal.listeners.MockingProgressListener;
import org.mockito.invocation.Invocation;
import org.mockito.verification.VerificationMode;
@SuppressWarnings("unchecked")
public class ThreadSafeMockingProgress implements MockingProgress, Serializable {
private static final long serialVersionUID = 6839454041642082618L;
private static ThreadLocal<MockingProgress> mockingProgress = new ThreadLocal<MockingProgress>();
static MockingProgress threadSafely() {
if (mockingProgress.get() == null) {
mockingProgress.set(new MockingProgressImpl());
}
return mockingProgress.get();
}
public void reportOngoingStubbing(IOngoingStubbing iOngoingStubbing) {
threadSafely().reportOngoingStubbing(iOngoingStubbing);
}
public IOngoingStubbing pullOngoingStubbing() {
return threadSafely().pullOngoingStubbing();
}
public void verificationStarted(VerificationMode verify) {
threadSafely().verificationStarted(verify);
}
public VerificationMode pullVerificationMode() {
return threadSafely().pullVerificationMode();
}
public void stubbingStarted() {
threadSafely().stubbingStarted();
}
public void validateState() {
threadSafely().validateState();
}
public void stubbingCompleted(Invocation invocation) {
threadSafely().stubbingCompleted(invocation);
}
public String toString() {
return threadSafely().toString();
}
public void reset() {
threadSafely().reset();
}
public void resetOngoingStubbing() {
threadSafely().resetOngoingStubbing();
}
public ArgumentMatcherStorage getArgumentMatcherStorage() {
return threadSafely().getArgumentMatcherStorage();
}
public void mockingStarted(Object mock, Class classToMock) {
threadSafely().mockingStarted
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal;
import java.util.List;
import org.mockito.internal.stubbing.InvocationContainer;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.VoidMethodStubbable;
@SuppressWarnings("unchecked")
public interface InternalMockHandler<T> extends MockHandler {
MockCreationSettings getMockSettings();
VoidMethodStubbable<T> voidMethodStubbable(T mock);
void setAnswersForStubbing(List<Answer> answers);
InvocationContainer getInvocationContainer();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.answers;
import org.mockito.exceptions.Reporter;
import org.mockito.invocation.Invocation;
import org.mockito.stubbing.Answer;
public class AnswersValidator {
private Reporter reporter = new Reporter();
public void validate(Answer<?> answer, Invocation invocation) {
MethodInfo methodInfo = new MethodInfo(invocation);
if (answer instanceof ThrowsException) {
validateException((ThrowsException) answer, methodInfo);
}
if (answer instanceof Returns) {
validateReturnValue((Returns) answer, methodInfo);
}
if (answer instanceof DoesNothing) {
validateDoNothing((DoesNothing) answer, methodInfo);
}
if (answer instanceof CallsRealMethods) {
validateMockingConcreteClass((CallsRealMethods) answer, methodInfo);
}
if (answer instanceof ReturnsArgumentAt) {
ReturnsArgumentAt returnsArgumentAt = (ReturnsArgumentAt) answer;
validateReturnArgIdentity(returnsArgumentAt, invocation);
}
}
private void validateReturnArgIdentity(ReturnsArgumentAt returnsArgumentAt, Invocation invocation) {
returnsArgumentAt.validateIndexWithinInvocationRange(invocation);
MethodInfo methodInfo = new MethodInfo(invocation);
if (!methodInfo.isValidReturnType(returnsArgumentAt.returnedTypeOnSignature(invocation))) {
new Reporter().wrongTypeOfArgumentToReturn(invocation, methodInfo.printMethodReturnType(),
returnsArgumentAt.returnedTypeOnSignature(invocation),
returnsArgumentAt.wantedArgumentPosition());
}
}
private void validateMockingConcreteClass(CallsRealMethods answer, MethodInfo methodInfo) {
if (methodInfo.isDeclaredOnInterface()) {
reporter.cannotCallRealMethodOnInterface();
}
}
private void validateDoNothing(DoesNothing answer, MethodInfo methodInfo) {
if (!methodInfo.isVoid()) {
reporter.onlyVoidMethodsCanBeSetToDoNothing();
}
}
private void validateReturnValue(Returns answer, MethodInfo methodInfo) {
if (methodInfo.isVoid()) {
reporter.cannotStubVoidMethodWithAReturnValue(methodInfo.getMethodName());
}
if (answer.returnsNull() && methodInfo.returnsPrimitive()) {
reporter
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("unchecked")
public class Primitives {
private static Map<Class<?>, Class<?>> primitiveTypes = new HashMap<Class<?>, Class<?>>();
private static Map<Class<?>, Object> primitiveOrWrapperDefaultValues = new HashMap<Class<?>, Object>();
/**
* Returns the primitive type of the given class.
* <p/>
* The passed class can be any class : <code>boolean.class</code>, <code>Integer.class</code>
* in witch case this method will return <code>boolean.class</code>, even <code>SomeObject.class</code>
* in which case <code>null</code> will be returned.
*
* @param clazz The class from which primitive type has to be retrieved
* @param <T> The type
* @return The primitive type if relevant, otherwise <code>null</code>
*/
public static <T> Class<T> primitiveTypeOf(Class<T> clazz) {
if (clazz.isPrimitive()) {
return clazz;
}
return (Class<T>) primitiveTypes.get(clazz);
}
/**
* Indicates if the given class is primitive type or a primitive wrapper.
*
* @param type The type to check
* @return <code>true</code> if primitive or wrapper, <code>false</code> otherwise.
*/
public static boolean isPrimitiveOrWrapper(Class<?> type) {
return primitiveOrWrapperDefaultValues.containsKey(type);
}
/**
* Returns the boxed default value for a primitive or a primitive wrapper.
*
* @param primitiveOrWrapperType The type to lookup the default value
* @return The boxed default values as defined in Java Language Specification,
* <code>null</code> if the type is neither a primitive nor a wrapper
*/
public static <T> T defaultValueForPrimitiveOrWrapper(Class<T> primitiveOrWrapperType) {
return (T) primitiveOrWrapperDefaultValues.get(primitiveOrWrapperType);
}
static {
primitive
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation;
import org.mockito.exceptions.Reporter;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.internal.exceptions.VerificationAwareInvocation;
import org.mockito.internal.invocation.realmethod.RealMethod;
import org.mockito.internal.reporting.PrintSettings;
import org.mockito.invocation.*;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Method call on a mock object.
* <p>
* Contains sequence number which should be globally unique and is used for
* verification in order.
* <p>
* Contains stack trace of invocation
*/
@SuppressWarnings("unchecked")
public class InvocationImpl implements Invocation, VerificationAwareInvocation {
private static final long serialVersionUID = 8240069639250980199L;
private final int sequenceNumber;
private final Object mock;
private final MockitoMethod method;
private final Object[] arguments;
private final Object[] rawArguments;
private final Location location;
private boolean verified;
private boolean isIgnoredForVerification;
final RealMethod realMethod;
private StubInfo stubInfo;
public InvocationImpl(Object mock, MockitoMethod mockitoMethod, Object[] args, int sequenceNumber, RealMethod realMethod) {
this.method = mockitoMethod;
this.mock = mock;
this.realMethod = realMethod;
this.arguments = ArgumentsProcessor.expandVarArgs(mockitoMethod.isVarArgs(), args);
this.rawArguments = args;
this.sequenceNumber = sequenceNumber;
this.location = new LocationImpl();
}
public Object getMock() {
return mock;
}
public Method getMethod() {
return method.getJavaMethod();
}
public Object[] getArguments() {
return arguments;
}
public boolean isVerified() {
return verified || isIgnoredForVerification;
}
public int getSequenceNumber() {
return sequenceNumber;
}
public boolean equals(Object o) {
if (o == null || !o.getClass().equals(this.getClass())) {
return false;
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> }
InvocationImpl other = (InvocationImpl) o;
return this.mock.equals(other.mock) && this.method.equals(other.method) && this.equalArguments(other.arguments);
}
private boolean equalArguments(Object[] arguments) {
return Arrays.equals(arguments, this.arguments);
}
@Override
public int hashCode() {
return 1;
}
public String toString() {
return new PrintSettings().print(ArgumentsProcessor.argumentsToMatchers(getArguments()), this);
}
public Location getLocation() {
return location;
}
public Object[] getRawArguments() {
return this.rawArguments;
}
public Object callRealMethod() throws Throwable {
if (this.getMethod().getDeclaringClass().isInterface()) {
new Reporter().cannotCallRealMethodOnInterface();
}
return realMethod.invoke(mock, rawArguments);
}
public void markVerified() {
this.verified = true;
}
public StubInfo stubInfo() {
return stubInfo;
}
public void markStubbed(StubInfo stubInfo) {
this.stubInfo = stubInfo;
}
public boolean isIgnoredForVerification() {
return isIgnoredForVerification;
}
public void ignoreForVerification() {
isIgnoredForVerification = true;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util.reflection;
import java.lang.reflect.Field;
public class Whitebox {
public static Object getInternalState(Object target, String field) {
Class<?> c = target.getClass();
try {
Field f = getFieldFromHierarchy(c, field);
f.setAccessible(true);
return f.get(target);
} catch (Exception e) {
throw new RuntimeException("Unable to get internal state on a private field. Please report to mockito mailing list.", e);
}
}
public static void setInternalState(Object target, String field, Object value) {
Class<?> c = target.getClass();
try {
Field f = getFieldFromHierarchy(c, field);
f.setAccessible(true);
f.set(target, value);
} catch (Exception e) {
throw new RuntimeException("Unable to set internal state on a private field. Please report to mockito mailing list.", e);
}
}
private static Field getFieldFromHierarchy(Class<?> clazz, String field) {
Field f = getField(clazz, field);
while (f == null && clazz != Object.class) {
clazz = clazz.getSuperclass();
f = getField(clazz, field);
}
if (f == null) {
throw new RuntimeException(
"You want me to get this field: '" + field +
"' on this class: '" + clazz.getSimpleName() +
"' but this field is not declared withing hierarchy of this class!");
}
return f;
}
private static Field getField(Class<?> clazz, String field) {
try {
return clazz.getDeclaredField(field);
} catch (NoSuchFieldException e) {
return null;
}
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>:
if (stubbingInProgress != null) {
Location temp = stubbingInProgress;
stubbingInProgress = null;
reporter.unfinishedStubbing(temp);
}
}
private void validateMostStuff() {
//State is cool when GlobalConfiguration is already loaded
//this cannot really be tested functionally because I cannot dynamically mess up org.mockito.configuration.MockitoConfiguration class
GlobalConfiguration.validate();
if (verificationMode != null) {
Location location = verificationMode.getLocation();
verificationMode = null;
reporter.unfinishedVerificationException(location);
}
getArgumentMatcherStorage().validateState();
}
public void stubbingCompleted(Invocation invocation) {
stubbingInProgress = null;
}
public String toString() {
return "iOngoingStubbing: " + iOngoingStubbing +
", verificationMode: " + verificationMode +
", stubbingInProgress: " + stubbingInProgress;
}
public void reset() {
stubbingInProgress = null;
verificationMode = null;
getArgumentMatcherStorage().reset();
}
public ArgumentMatcherStorage getArgumentMatcherStorage() {
return argumentMatcherStorage;
}
public void mockingStarted(Object mock, Class classToMock) {
if (listener != null && listener instanceof MockingStartedListener) {
((MockingStartedListener) listener).mockingStarted(mock, classToMock);
}
validateMostStuff();
}
public void setListener(MockingProgressListener listener) {
this.listener = listener;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.progress;
import org.mockito.MockSettings;
import org.mockito.internal.listeners.MockingProgressListener;
import org.mockito.invocation.Invocation;
import org.mockito.verification.VerificationMode;
@SuppressWarnings("unchecked")
public interface MockingProgress {
void reportOngoingStubbing(IOngoingStubbing iOngoingStubbing);
IOngoingStubbing pullOngoingStubbing();
void verificationStarted(VerificationMode verificationMode);
VerificationMode pullVerificationMode();
void stubbingStarted();
void stubbingCompleted(Invocation invocation);
void validateState();
void reset();
/**
* Removes ongoing stubbing so that in case the framework is misused
* state validation errors are more accurate
*/
void resetOngoingStubbing();
ArgumentMatcherStorage getArgumentMatcherStorage();
void mockingStarted(Object mock, Class classToMock);
void setListener(MockingProgressListener listener);
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.handler;
import org.mockito.exceptions.Reporter;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.listeners.NotifiedMethodInvocationReport;
import org.mockito.internal.stubbing.InvocationContainer;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MockHandler;
import org.mockito.listeners.InvocationListener;
import org.mockito.mock.MockCreationSettings;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.VoidMethodStubbable;
import java.util.List;
/**
* Handler, that call all listeners wanted for this mock, before delegating it
* to the parameterized handler.
*
* Also imposterize MockHandlerImpl, delegate all call of InternalMockHandler to the real mockHandler
*/
class InvocationNotifierHandler<T> implements MockHandler, InternalMockHandler<T> {
private List<InvocationListener> invocationListeners;
private InternalMockHandler<T> mockHandler;
public InvocationNotifierHandler(InternalMockHandler<T> mockHandler, MockCreationSettings settings) {
this.mockHandler = mockHandler;
this.invocationListeners = settings.getInvocationListeners();
}
public Object handle(Invocation invocation) throws Throwable {
try {
Object returnedValue = mockHandler.handle(invocation);
notifyMethodCall(invocation, returnedValue);
return returnedValue;
} catch (Throwable t){
notifyMethodCallException(invocation, t);
throw t;
}
}
private void notifyMethodCall(Invocation invocation, Object returnValue) {
for (InvocationListener listener : invocationListeners) {
try {
listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, returnValue));
} catch(Throwable listenerThrowable) {
new Reporter().invocationListenerThrewException(listener, listenerThrowable);
}
}
}
private void notifyMethodCallException(Invocation invocation, Throwable exception) {
for (InvocationListener listener : invocationListeners) {
try {
listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, exception));
} catch(Throwable listenerThrowable) {
new Reporter
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>().invocationListenerThrewException(listener, listenerThrowable);
}
}
}
public MockCreationSettings getMockSettings() {
return mockHandler.getMockSettings();
}
public VoidMethodStubbable<T> voidMethodStubbable(T mock) {
return mockHandler.voidMethodStubbable(mock);
}
public void setAnswersForStubbing(List<Answer> answers) {
mockHandler.setAnswersForStubbing(answers);
}
public InvocationContainer getInvocationContainer() {
return mockHandler.getInvocationContainer();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util;
import org.mockito.internal.creation.DelegatingMethod;
import org.mockito.internal.invocation.MockitoMethod;
import java.io.Serializable;
import java.lang.reflect.Method;
public class ObjectMethodsGuru implements Serializable {
private static final long serialVersionUID = -1286718569065470494L;
public boolean isToString(Method method) {
return isToString(new DelegatingMethod(method));
}
public boolean isToString(MockitoMethod method) {
return method.getReturnType() == String.class
&& method.getParameterTypes().length == 0
&& method.getName().equals("toString");
}
public boolean isEqualsMethod(Method method) {
return method.getName().equals("equals")
&& method.getParameterTypes().length == 1
&& method.getParameterTypes()[0] == Object.class;
}
public boolean isHashCodeMethod(Method method) {
return method.getName().equals("hashCode")
&& method.getParameterTypes().length == 0;
}
public boolean isCompareToMethod(Method method) {
return Comparable.class.isAssignableFrom(method.getDeclaringClass())
&& method.getName().equals("compareTo")
&& method.getParameterTypes().length == 1
&& method.getParameterTypes()[0] == method.getDeclaringClass();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.answers;
import java.io.Serializable;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class DoesNothing implements Answer<Object>, Serializable {
private static final long serialVersionUID = 4840880517740698416L;
public Object answer(InvocationOnMock invocation) throws Throwable {
return null;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> <ul>
* <li>Create a proxy object that implements {@code settings.typeToMock} and potentially also {@code settings.extraInterfaces}.</li>
* <li>You may use the information from {@code settings} to create/configure your proxy object.</li>
* <li>Your proxy object should carry the {@code handler} with it. For example, if you generate byte code
* to create the proxy you could generate an extra field to keep the {@code handler} with the generated object.
* Your implementation of {@code MockMaker} is required to provide this instance of {@code handler} when
* {@link #getHandler(Object)} is called.
* </li>
* </ul>
*
* @param settings - mock creation settings like type to mock, extra interfaces and so on.
* @param handler See {@link org.mockito.invocation.MockHandler}.
* <b>Do not</b> provide your own implementation at this time. Make sure your implementation of
* {@link #getHandler(Object)} will return this instance.
* @param <T> Type of the mock to return, actually the <code>settings.getTypeToMock</code>.
* @return The mock instance.
* @since 1.9.5
*/
<T> T createMock(
MockCreationSettings<T> settings,
MockHandler handler
);
/**
* Returns the handler for the {@code mock}. <b>Do not</b> provide your own implementations at this time
* because the work on the {@link MockHandler} api is not completed.
* Use the instance provided to you by Mockito at {@link #createMock} or {@link #resetMock}.
*
* @param mock The mock instance.
* @return may return null - it means that there is no handler attached to provided object.
* This means the passed object is not really a Mockito mock.
* @since 1.9.5
*/
MockHandler getHandler(Object mock);
/**
* Replaces the existing handler on {@code mock} with {@code newHandler}.
*
* <p>The invocation handler actually store invocations to achieve
* stubbing and verification. In order to reset the mock, we pass
* a new instance of the invocation handler.</
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>p>
*
* <p>Your implementation should make sure the {@code newHandler} is correctly associated to passed {@code mock}</p>
*
* @param mock The mock instance whose invocation handler is to be replaced.
* @param newHandler The new invocation handler instance.
* @param settings The mock settings - should you need to access some of the mock creation details.
* @since 1.9.5
*/
void resetMock(
Object mock,
MockHandler newHandler,
MockCreationSettings settings
);
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation;
import org.hamcrest.Matcher;
import org.mockito.exceptions.Reporter;
import org.mockito.internal.matchers.LocalizedMatcher;
import org.mockito.internal.progress.ArgumentMatcherStorage;
import org.mockito.invocation.Invocation;
import java.io.Serializable;
import java.util.List;
@SuppressWarnings("unchecked")
public class MatchersBinder implements Serializable {
private static final long serialVersionUID = -311433939339443463L;
public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
List<LocalizedMatcher> lastMatchers = argumentMatcherStorage.pullLocalizedMatchers();
validateMatchers(invocation, lastMatchers);
InvocationMatcher invocationWithMatchers = new InvocationMatcher(invocation, (List<Matcher>)(List) lastMatchers);
return invocationWithMatchers;
}
private void validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers) {
if (!lastMatchers.isEmpty()) {
int recordedMatchersSize = lastMatchers.size();
int expectedMatchersSize = invocation.getArguments().length;
if (expectedMatchersSize != recordedMatchersSize) {
new Reporter().invalidUseOfMatchers(expectedMatchersSize, lastMatchers);
}
}
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation;
import org.hamcrest.Matcher;
import org.mockito.internal.matchers.MatcherDecorator;
import org.mockito.internal.matchers.VarargMatcher;
import org.mockito.invocation.Invocation;
import java.util.List;
@SuppressWarnings("unchecked")
public class ArgumentsComparator {
public boolean argumentsMatch(InvocationMatcher invocationMatcher, Invocation actual) {
Object[] actualArgs = actual.getArguments();
return argumentsMatch(invocationMatcher, actualArgs) || varArgsMatch(invocationMatcher, actual);
}
public boolean argumentsMatch(InvocationMatcher invocationMatcher, Object[] actualArgs) {
if (actualArgs.length != invocationMatcher.getMatchers().size()) {
return false;
}
for (int i = 0; i < actualArgs.length; i++) {
if (!invocationMatcher.getMatchers().get(i).matches(actualArgs[i])) {
return false;
}
}
return true;
}
//ok, this method is a little bit messy but the vararg business unfortunately is messy...
private boolean varArgsMatch(InvocationMatcher invocationMatcher, Invocation actual) {
if (!actual.getMethod().isVarArgs()) {
//if the method is not vararg forget about it
return false;
}
//we must use raw arguments, not arguments...
Object[] rawArgs = actual.getRawArguments();
List<Matcher> matchers = invocationMatcher.getMatchers();
if (rawArgs.length != matchers.size()) {
return false;
}
for (int i = 0; i < rawArgs.length; i++) {
Matcher m = matchers.get(i);
//it's a vararg because it's the last array in the arg list
if (rawArgs[i] != null && rawArgs[i].getClass().isArray() && i == rawArgs.length-1) {
Matcher actualMatcher;
//this is necessary as the framework often decorates matchers
if (m instanceof MatcherDecorator) {
actualMatcher = ((MatcherDecorator)m).getActualMatcher();
} else {
actualMatcher = m;
}
//this is
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.defaultanswers;
import java.io.Serializable;
import org.mockito.internal.MockitoCore;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class ReturnsMocks implements Answer<Object>, Serializable {
private static final long serialVersionUID = -6755257986994634579L;
private MockitoCore mockitoCore = new MockitoCore();
private Answer<Object> delegate = new ReturnsMoreEmptyValues();
public Object answer(InvocationOnMock invocation) throws Throwable {
Object ret = delegate.answer(invocation);
if (ret != null) {
return ret;
}
return returnValueFor(invocation.getMethod().getReturnType());
}
Object returnValueFor(Class<?> clazz) {
if (!mockitoCore.isTypeMockable(clazz)) {
return null;
}
return mockitoCore.mock(clazz, new MockSettingsImpl().defaultAnswer(this));
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>
* TODO offer a way to disable completely this behavior, or maybe enable this behavior only with a specific setting
* TODO check the class is mockable in the deserialization side
*
* @see CglibMockMaker
* @see MethodInterceptorFilter
* @author Brice Dutheil
* @since 1.9.6
*/
@Incubating
public class AcrossJVMSerializationFeature implements Serializable {
private static final long serialVersionUID = 7411152578314420778L;
private static final String MOCKITO_PROXY_MARKER = "MockitoProxyMarker";
private boolean instanceLocalCurrentlySerializingFlag = false;
private Lock mutex = new ReentrantLock();
public boolean isWriteReplace(Method method) {
return method.getReturnType() == Object.class
&& method.getParameterTypes().length == 0
&& method.getName().equals("writeReplace");
}
/**
* Custom implementation of the <code>writeReplace</code> method for serialization.
*
* Here's how it's working and why :
* <ol>
* <li>
* <p>When first entering in this method, it's because some is serializing the mock, with some code like :
* <pre class="code"><code class="java">
* objectOutputStream.writeObject(mock);
* </code></pre>
* So, {@link ObjectOutputStream} will track the <code>writeReplace</code> method in the instance and
* execute it, which is wanted to replace the mock by another type that will encapsulate the actual mock.
* At this point, the code will return an {@link AcrossJVMMockSerializationProxy}.</p>
* </li>
* <li>
* <p>Now, in the constructor {@link AcrossJVMMockSerializationProxy#AcrossJVMMockSerializationProxy(Object)}
* the mock is being serialized in a custom way (using {@link MockitoMockObjectOutputStream}) to a
* byte array. So basically it means the code is performing double nested serialization of the passed
* <code>mockitoMock</code>.</p>
*
* <p>However the <code>ObjectOutputStream</code> will still detect the custom
*
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> <code>writeReplace</code> and execute it.
* <em>(For that matter disabling replacement via {@link ObjectOutputStream#enableReplaceObject(boolean)}
* doesn't disable the <code>writeReplace</code> call, but just just toggle replacement in the
* written stream, <strong><code>writeReplace</code> is always called by
* <code>ObjectOutputStream</code></strong>.)</em></p>
*
* <p>In order to avoid this recursion, obviously leading to a {@link StackOverflowError}, this method is using
* a flag that marks the mock as already being replaced, and then shouldn't replace itself again.
* <strong>This flag is local to this class</strong>, which means the flag of this class unfortunately needs
* to be protected against concurrent access, hence the reentrant lock.</p>
* </li>
* </ol>
*
*
* @param mockitoMock The Mockito mock to be serialized.
* @return A wrapper ({@link AcrossJVMMockSerializationProxy}) to be serialized by the calling ObjectOutputStream.
* @throws ObjectStreamException
*/
public Object writeReplace(Object mockitoMock) throws ObjectStreamException {
try {
// reentrant lock for critical section. could it be improved ?
mutex.lock();
// mark started flag // per thread, not per instance
// temporary loosy hack to avoid stackoverflow
if(mockIsCurrentlyBeingReplaced()) {
return mockitoMock;
}
mockReplacementStarted();
return new AcrossJVMMockSerializationProxy(mockitoMock);
} catch (IOException ioe) {
MockUtil mockUtil = new MockUtil();
MockName mockName = mockUtil.getMockName(mockitoMock);
String mockedType = mockUtil.getMockSettings(mockitoMock).getTypeToMock().getCanonicalName();
throw new MockitoSerializationIssue(join(
"The mock '" + mockName + "' of type '" + mockedType + "'",
"The Java Standard Serialization reported an '" + ioe.getClass().getSimpleName() + "' saying :",
" " + ioe.getMessage()
), ioe);
} finally {
// unmark
mockReplacementCompleted();
mutex.unlock();
}
}
private void mockReplacementCompleted() {
instanceLocalCurrentlySerial
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>izingFlag = false;
}
private void mockReplacementStarted() {
instanceLocalCurrentlySerializingFlag = true;
}
private boolean mockIsCurrentlyBeingReplaced() {
return instanceLocalCurrentlySerializingFlag;
}
/**
* Enable serialization serialization that will work across classloaders / and JVM.
*
* <p>Only enable if settings says the mock should be serializable. In this case add the
* {@link AcrossJVMMockitoMockSerializable} to the extra interface list.</p>
*
* @param settings Mock creation settings.
* @param <T> Type param to not be bothered by the generics
*/
public <T> void enableSerializationAcrossJVM(MockCreationSettings<T> settings) {
if (settings.getSerializableMode() == SerializableMode.ACROSS_CLASSLOADERS) {
// havin faith that this set is modifiable
// TODO use a proper way to add the interface
settings.getExtraInterfaces().add(AcrossJVMMockitoMockSerializable.class);
}
}
/**
* This is the serialization proxy that will encapsulate the real mock data as a byte array.
*
* <p>When called in the constructor it will serialize the mock in a byte array using a
* custom {@link MockitoMockObjectOutputStream} that will annotate the mock class in the stream.
* other information are used in this class in order to facilitate deserialization.
* </p>
*
* <p>Deserialization of the mock will be performed by the {@link #readResolve()} method via
* the custom {@link MockitoMockObjectInputStream} that will be in charge of creating the mock class.</p>
*/
public static class AcrossJVMMockSerializationProxy implements Serializable {
private static final long serialVersionUID = -7600267929109286514L;
private byte[] serializedMock;
private Class typeToMock;
private Set<Class> extraInterfaces;
/**
* Creates the wrapper that be used in the serialization stream.
*
* <p>Immediately serializes the Mockito mock using specifically crafted {@link MockitoMockObjectOutputStream},
* in a byte array.</p>
*
* @param mockitoMock The Mockito mock to serialize.
* @throws IOException
*/
public Across
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>JVMMockSerializationProxy(Object mockitoMock) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new MockitoMockObjectOutputStream(out);
objectOutputStream.writeObject(mockitoMock);
objectOutputStream.close();
out.close();
MockCreationSettings mockSettings = new MockUtil().getMockSettings(mockitoMock);
this.serializedMock = out.toByteArray();
this.typeToMock = mockSettings.getTypeToMock();
this.extraInterfaces = mockSettings.getExtraInterfaces();
}
/**
* Resolves the proxy to a new deserialized instance of the Mockito mock.
*
* <p>Uses the custom crafted {@link MockitoMockObjectInputStream} to deserialize the mock.</p>
*
* @return A deserialized instance of the Mockito mock.
* @throws ObjectStreamException
*/
private Object readResolve() throws ObjectStreamException {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(serializedMock);
ObjectInputStream objectInputStream = new MockitoMockObjectInputStream(bis, typeToMock, extraInterfaces);
Object deserializedMock = objectInputStream.readObject();
bis.close();
objectInputStream.close();
return deserializedMock;
} catch (IOException ioe) {
throw new MockitoSerializationIssue(join(
"Mockito mock cannot be deserialized to a mock of '" + typeToMock.getCanonicalName() + "'. The error was :",
" " + ioe.getMessage(),
"If you are unsure what is the reason of this exception, feel free to contact us on the mailing list."
), ioe);
} catch (ClassNotFoundException cce) {
throw new MockitoSerializationIssue(join(
"A class couldn't be found while deserializing a Mockito mock, you should check your classpath. The error was :",
" " + cce.getMessage(),
"If you are still unsure what is the reason of this exception, feel free to contact us on the mailing list."
), cce);
}
}
}
/**
* Special Mockito aware <code>ObjectInputStream</code> that will resolve the Mockito proxy class.
*
* <p>
* This specificaly crafted ObjectInoutStream has the most important role to resolve the Mockito generated
* class. It is doing so via the {@link #resolveClass(java.io.ObjectStreamClass)} which looks in the stream
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>> if not marked as a Mockito, <code>false</code> if the class annotation marks a Mockito mock.
* @throws IOException
* @throws ClassNotFoundException
*/
private boolean notMarkedAsAMockitoMock(Object marker) throws IOException, ClassNotFoundException {
return !MOCKITO_PROXY_MARKER.equals(marker);
}
}
/**
* Special Mockito aware <code>ObjectOutputStream</code>.
*
* <p>
* This output stream has the role of marking in the stream the Mockito class. This
* marking process is necessary to identify the proxy class that will need to be recreated.
*
* The mirror method used for deserializing the mock is
* {@link MockitoMockObjectInputStream#resolveClass(ObjectStreamClass)}.
* </p>
*
*/
private static class MockitoMockObjectOutputStream extends ObjectOutputStream {
private static final String NOTHING = "";
private MockUtil mockUtil = new MockUtil();
public MockitoMockObjectOutputStream(ByteArrayOutputStream out) throws IOException {
super(out);
}
/**
* Annotates (marks) the class if this class is a Mockito mock.
*
* @param cl The class to annotate.
* @throws IOException
*/
@Override
protected void annotateClass(Class<?> cl) throws IOException {
writeObject(mockitoProxyClassMarker(cl));
// might be also useful later, for embedding classloader info ...maybe ...maybe not
}
/**
* Returns the Mockito marker if this class is a Mockito mock.
*
* @param cl The class to mark.
* @return The marker if this is a Mockito proxy class, otherwise returns a void marker.
*/
private String mockitoProxyClassMarker(Class<?> cl) {
if (AcrossJVMMockitoMockSerializable.class.isAssignableFrom(cl)) {
return MOCKITO_PROXY_MARKER;
} else {
return NOTHING;
}
}
}
/**
* Simple interface that hold a correct <code>writeReplace</code> signature that can be seen by an
* <code>ObjectOutputStream</code>.
*
* It will be applied before the creation of the mock when the mock setting says it should serializable.
*
* @see #enableSerializationAcrossJVM(org.mockito.mock.MockCreationSettings)
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> */
public static interface AcrossJVMMockitoMockSerializable {
public Object writeReplace() throws java.io.ObjectStreamException;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS></li>
* </ul>
*
* <p>The difference with the regular spy:
* <ul>
* <li>
* The regular spy ({@link #spy(Object)}) contains <strong>all</strong> state from the spied instance
* and the methods are invoked on the spy. The spied instance is only used at mock creation to copy the state from.
* If you call a method on a regular spy and it internally calls other methods on this spy, those calls are remembered
* for verifications, and they can be effectively stubbed.
* </li>
* <li>
* The mock that delegates simply delegates all methods to the delegate.
* The delegate is used all the time as methods are delegated onto it.
* If you call a method on a mock that delegates and it internally calls other methods on this mock,
* those calls are <strong>not</strong> remembered for verifications, stubbing does not have effect on them, too.
* Mock that delegates is less powerful than the regular spy but it is useful when the regular spy cannot be created.
* </li>
* </ul>
*
* <p>
* See more information in docs for {@link AdditionalAnswers#delegatesTo(Object)}.
*
*
*
*
* <h3 id="28">28. (**New**) <a class="meaningful_link" href="#mock_maker_plugin"><code>MockMaker</code> API</a> (Since 1.9.5)</h3>
* <p>Driven by requirements and patches from Google Android guys Mockito now offers an extension point
* that allows replacing the proxy generation engine. By default, Mockito uses cglib to create dynamic proxies.
* <p>The extension point is for advanced users that want to extend Mockito. For example, it is now possible
* to use Mockito for Android testing with a help of dexmaker.
* <p>For more details, motivations and examples please refer to
* the docs for {@link org.mockito.plugins.MockMaker}.
*
*/
@SuppressWarnings("unchecked")
public class Mockito extends Matchers {
static final MockitoCore MOCKITO_CORE = new
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> MockitoCore();
/**
* The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
* Typically it just returns some empty value.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation first tries the global configuration.
* If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
*/
public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS.get();
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException.
* This implementation of Answer <b>returns SmartNull instead of null</b>.
* <code>SmartNull</code> gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.
* <p>
* <code>ReturnsSmartNulls</code> first tries to return ordinary return values (see {@link ReturnsMoreEmptyValues})
* then it tries to return SmartNull. If the return type is final then plain null is returned.
* <p>
* <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 2.0.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = (Foo.class, RETURNS_SMART_NULLS);
*
* //calling unstubbed method here:
* Stuff stuff = mock.getStuff();
*
* //using object returned by unstubbed call:
* stuff.doSomething();
*
* //Above doesn't yield NullPointerException this time!
* //Instead, SmartNullPointerException is thrown.
* //Exception's cause links
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> to unstubbed <i>mock.getStuff()</i> - just click on the stack trace.
* </code></pre>
*/
public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS.get();
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* <p>
* ReturnsMocks first tries to return ordinary return values (see {@link ReturnsMoreEmptyValues})
* then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain null is returned.
* <p>
*/
public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS.get();
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
* <p>
* Example that shows how deep stub works:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
*
* // note that we're stubbing a chain of methods here: getBar().getName()
* when(mock.getBar().getName()).thenReturn("deep");
*
* // note that we're chaining method calls: getBar().getName()
* assertEquals("deep", mock.getBar().getName());
* </code></pre>
* </p>
*
* <p>
* <strong>WARNING: </strong>
* This feature should rarely be required for regular clean code! Leave it for legacy code.
* Mocking a mock to return a mock, to return a mock, (...), to return something meaningful
* hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).
* </p>
*
* <p>
* Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>.
* </p>
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>("the docks").getStreet()).getLongName();
* inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName();
* inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName();
* </code></pre>
* </p>
*
* <p>
* How deep stub work internally?
* <pre class="code"><code class="java">
* //this:
* Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
* when(mock.getBar().getName(), "deep");
*
* //is equivalent of
* Foo foo = mock(Foo.class);
* Bar bar = mock(Bar.class);
* when(foo.getBar()).thenReturn(bar);
* when(bar.getName()).thenReturn("deep");
* </code></pre>
* </p>
*
* <p>
* This feature will not work when any return type of methods included in the chain cannot be mocked
* (for example: is a primitive or a final class). This is because of java type system.
* </p>
*/
public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS.get();
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* When this implementation is used, unstubbed methods will delegate to the real implementation.
* This is a way to create a partial mock object that calls real methods by default.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
*
* // this calls the real implementation of Foo.getSomething()
* value = mock.getSomething();
*
* when(mock.getSomething()).thenReturn(fakeValue);
*
* // now fakeValue is returned
* value = mock.getSomething();
* </code></pre>
*/
public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS.get();
/**
* Creates mock object of given class or interface.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @return mock object
*/
public static <T> T mock(Class<T> classToMock) {
return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}
/**
* Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
* <p>
* Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.
* <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
* <p>
* <b>If you use <code>@Mock</code> annotation then you've got naming mocks for free!</b> <code>@Mock</code> uses field name as mock name. {@link Mock Read more.}
* <p>
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @param name of the mock
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> * @return mock object
*/
public static <T> T mock(Class<T> classToMock, String name) {
return mock(classToMock, withSettings()
.name(name)
.defaultAnswer(RETURNS_DEFAULTS));
}
/**
* Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information.
* Can be used to find out if given object is a Mockito mock
* or to find out if a given mock is a spy or mock.
* <p>
* In future Mockito versions MockingDetails may grow and provide other useful information about the mock,
* e.g. invocations, stubbing info, etc.
*
* @param toInspect - object to inspect
* @return A {@link org.mockito.MockingDetails} instance.
* @since 1.9.5
*/
@Incubating
public static MockingDetails mockingDetails(Object toInspect) {
return MOCKITO_CORE.mockingDetails(toInspect);
}
/**
* <b>Deprecated : Please use mock(Foo.class, defaultAnswer);</b>
* <p>
* See {@link Mockito#mock(Class, Answer)}
* <p>
* Why it is deprecated? ReturnValues is being replaced by Answer
* for better consistency & interoperability of the framework.
* Answer interface has been in Mockito for a while and it has the same responsibility as ReturnValues.
* There's no point in mainting exactly the same interfaces.
* <p>
* Creates mock with a specified strategy for its return values.
* It's quite advanced feature and typically you don't need it to write decent tests.
* However it can be helpful when working with legacy systems.
* <p>
* Obviously return values are used only when you don't stub the method call.
*
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnReturnValues());
* </code></pre>
*
* <p>See examples in javadoc for {@link Mockito} class</p>
*
* @param classToMock class or interface to mock
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>
* @param returnValues default return values for unstubbed methods
*
* @return mock object
*
* @deprecated <b>Please use mock(Foo.class, defaultAnswer);</b>
*/
@Deprecated
public static <T> T mock(Class<T> classToMock, ReturnValues returnValues) {
return mock(classToMock, withSettings().defaultAnswer(new AnswerReturnValuesAdapter(returnValues)));
}
/**
* Creates mock with a specified strategy for its answers to interactions.
* It's quite advanced feature and typically you don't need it to write decent tests.
* However it can be helpful when working with legacy systems.
* <p>
* It is the default answer so it will be used <b>only when you don't</b> stub the method call.
*
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
* </code></pre>
*
* <p>See examples in javadoc for {@link Mockito} class</p>
*
* @param classToMock class or interface to mock
* @param defaultAnswer default answer for unstubbed methods
*
* @return mock object
*/
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {
return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
}
/**
* Creates a mock with some non-standard settings.
* <p>
* The number of configuration points for a mock grows
* so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods.
* Hence {@link MockSettings}.
* <pre class="code"><code class="java">
* Listener mock = mock(Listener.class, withSettings()
* .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));
* );
* </code></pre>
* <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks?
* Is the code under test so complicated that it requires non-standard mocks?
* Would
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> verifyNoMoreInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
* Verifies that no interactions happened on given mocks.
* <pre class="code"><code class="java">
* verifyZeroInteractions(mockOne, mockTwo);
* </code></pre>
* This method will also detect invocations
* that occurred before the test method, for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
* <p>
* See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
*/
public static void verifyZeroInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
* <pre class="code"><code class="java">
* //Instead of:
* stubVoid(mock).toThrow(e).on().someVoidMethod();
*
* //Please do:
* doThrow(e).when(mock).someVoidMethod();
* </code></pre>
*
* doThrow() replaces stubVoid() because of improved readability and consistency with the family of doAnswer() methods.
* <p>
* Originally, <code>stubVoid()</code> was used for stubbing void methods with exceptions. E.g:
*
* <pre class="code"><code class="java">
* stubVoid(mock).toThrow(new RuntimeException()).on().someMethod();
*
* //you can stub with different behavior for consecutive calls.
* //Last stubbing (e.g. toReturn()) determines the behavior for further consecutive calls.
* stubVoid(mock)
* .toThrow(new RuntimeException())
* .toReturn()
* .on().someMethod();
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @deprecated Use {@link Mockito#doThrow(Throwable)} method for stubbing voids
*
* @param mock
* to stub
* @return stub
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>mock).someMethod();
* </code></pre>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param answer to answer when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doAnswer(Answer answer) {
return MOCKITO_CORE.doAnswer(answer);
}
/**
* Use <code>doNothing()</code> for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by default!</b>
* However, there are rare situations when doNothing() comes handy:
* <p>
* <ol>
* <li>Stubbing consecutive calls on a void method:
* <pre class="code"><code class="java">
* doNothing().
* doThrow(new RuntimeException())
* .when(mock).someVoidMethod();
*
* //does nothing the first time:
* mock.someVoidMethod();
*
* //throws RuntimeException the next time:
* mock.someVoidMethod();
* </code></pre>
* </li>
* <li>When you spy real objects and you want the void method to do nothing:
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //let's make clear() do nothing
* doNothing().when(spy).clear();
*
* spy.add("one");
*
* //clear() does nothing, so the list still contains "one"
* spy.clear();
* </code></pre>
* </li>
* </ol>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return stubber - to select a method for stubbing
*/
public static Stubber doNothing() {
return MOCKITO_CORE.doAnswer(new DoesNothing());
}
/**
* Use <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
* <p>
* <b>Beware that {@link Mockito#when(Object)} is always recommended for
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> stubbing because it is argument type-safe
* and more readable</b> (especially when stubbing consecutive calls).
* <p>
* Here are those rare occasions when doReturn() comes handy:
* <p>
*
* <ol>
* <li>When spying real objects and calling real methods on a spy brings side effects
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing:
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Overriding a previous exception-stubbing:
* <pre class="code"><code class="java">
* when(mock.foo()).thenThrow(new RuntimeException());
*
* //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
* when(mock.foo()).thenReturn("bar");
*
* //You have to use doReturn() for stubbing:
* doReturn("bar").when(mock).foo();
* </code></pre>
* </li>
* </ol>
*
* Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though.
* Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
* overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param toBeReturned to be returned when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doReturn(Object toBeReturned) {
return MOCKITO_CORE.doAnswer(new Returns(toBeReturned));
}
/**
* Creates {@link org.mockito.InOrder} object that allows
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> verifying mocks in order.
*
* <pre class="code"><code class="java">
* InOrder inOrder = inOrder(firstMock, secondMock);
*
* inOrder.verify(firstMock).add("was called first");
* inOrder.verify(secondMock).add("was called second");
* </code></pre>
*
* Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one
* but only those that you are interested in testing in order.
* <p>
* Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
* <p>
* <code>InOrder</code> verification is 'greedy'. You will hardly every notice it but
* if you want to find out more search for 'greedy' on the Mockito
* <a href="http://code.google.com/p/mockito/w/list">wiki pages</a>.
* <p>
* As of Mockito 1.8.4 you can verifyNoMoreInvocations() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified in order
*
* @return InOrder object to be used to verify in order
*/
public static InOrder inOrder(Object... mocks) {
return MOCKITO_CORE.inOrder(mocks);
}
/**
* Ignores stubbed methods of given mocks for the sake of verification.
* Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
* Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
* <p>
* <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of <code>verifyNoMoreInteractions(ignoreStubs(...));</code>
* Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
* for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>class);
* when(mock.get(0)).thenReturn("foo");
*
* list.add(0);
* System.out.println(list.get(0)); //we don't want to verify this
* list.clear();
*
* InOrder inOrder = inOrder(ignoreStubs(list));
* inOrder.verify(list).add(0);
* inOrder.verify(list).clear();
* inOrder.verifyNoMoreInteractions();
* </code></pre>
*
* @since 1.9.0
* @param mocks input mocks that will be changed
* @return the same mocks that were passed in as parameters
*/
public static Object[] ignoreStubs(Object... mocks) {
return MOCKITO_CORE.ignoreStubs(mocks);
}
/**
* Allows verifying exact number of invocations. E.g:
* <pre class="code"><code class="java">
* verify(mock, times(2)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param wantedNumberOfInvocations wanted number of invocations
*
* @return verification mode
*/
public static VerificationMode times(int wantedNumberOfInvocations) {
return VerificationModeFactory.times(wantedNumberOfInvocations);
}
/**
* Alias to <code>times(0)</code>, see {@link Mockito#times(int)}
* <p>
* Verifies that interaction did not happen. E.g:
* <pre class="code"><code class="java">
* verify(mock, never()).someMethod();
* </code></pre>
*
* <p>
* If you want to verify there were NO interactions with the mock
* check out {@link Mockito#verifyZeroInteractions(Object...)}
* or {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode never() {
return times(0);
}
/**
* Allows at-least-once verification. E.g:
* <pre class="code"><code class="java">
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.invocation;
import org.mockito.Incubating;
import java.io.Serializable;
/**
* Mockito handler of an invocation on a mock. This is a core part of the API, the heart of Mockito.
* See also the {@link org.mockito.plugins.MockMaker}.
* <p>
* This api is work in progress. Do not provide your own implementations.
* Mockito will provide you with the implementation via other {@link org.mockito.plugins.MockMaker} methods.
*/
@Incubating
public interface MockHandler extends Serializable {
/**
* Takes an invocation object and handles it.
* <p>
* The default implementation provided by Mockito handles invocations by recording
* method calls on mocks for further verification, captures the stubbing information when mock is stubbed,
* returns the stubbed values for invocations that have been stubbed, and much more.
*
* @param invocation The invocation to handle
* @return Result
* @throws Throwable Throwable
*/
@Incubating
Object handle(Invocation invocation) throws Throwable;
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.mock;
import org.mockito.Incubating;
import org.mockito.listeners.InvocationListener;
import org.mockito.stubbing.Answer;
import java.util.List;
import java.util.Set;
/**
* Informs about the mock settings. An immutable view of {@link org.mockito.MockSettings}.
*/
@Incubating
public interface MockCreationSettings<T> {
/**
* Mocked type. An interface or class the mock should implement / extend.
*/
Class<T> getTypeToMock();
/**
* the extra interfaces the mock object should implement.
*/
Set<Class> getExtraInterfaces();
/**
* the name of this mock, as printed on verification errors; see {@link org.mockito.MockSettings#name}.
*/
MockName getMockName();
/**
* the default answer for this mock, see {@link org.mockito.MockSettings#defaultAnswer}.
*/
Answer getDefaultAnswer();
/**
* the spied instance - needed for spies.
*/
Object getSpiedInstance();
/**
* if the mock is serializable, see {@link org.mockito.MockSettings#serializable}.
*/
boolean isSerializable();
/**
* @return the serializable mode of this mock
*/
SerializableMode getSerializableMode();
/**
* Whether the mock is only for stubbing, i.e. does not remember
* parameters on its invocation and therefore cannot
* be used for verification
*/
boolean isStubOnly();
/**
* the invocation listeners attached to this mock, see {@link org.mockito.MockSettings#invocationListeners}.
*/
List<InvocationListener> getInvocationListeners();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing.answers;
import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
import org.mockito.internal.util.MockUtil;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
public class ThrowsException implements Answer<Object>, Serializable {
private static final long serialVersionUID = 1128820328555183980L;
private final Throwable throwable;
private final ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();
public ThrowsException(Throwable throwable) {
this.throwable = throwable;
}
public Object answer(InvocationOnMock invocation) throws Throwable {
if (new MockUtil().isMock(throwable)) {
throw throwable;
}
Throwable t = throwable.fillInStackTrace();
filter.filter(t);
throw t;
}
public Throwable getThrowable() {
return throwable;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.handler;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.progress.HandyReturnValues;
import org.mockito.internal.stubbing.InvocationContainer;
import org.mockito.invocation.Invocation;
import org.mockito.mock.MockCreationSettings;
import org.mockito.stubbing.VoidMethodStubbable;
import java.util.List;
/**
* Protects the results from delegate MockHandler. Makes sure the results are valid.
*
* by Szczepan Faber, created at: 5/22/12
*/
class NullResultGuardian implements InternalMockHandler {
private final InternalMockHandler delegate;
public NullResultGuardian(InternalMockHandler delegate) {
this.delegate = delegate;
}
public Object handle(Invocation invocation) throws Throwable {
Object result = delegate.handle(invocation);
Class<?> returnType = invocation.getMethod().getReturnType();
if(result == null && returnType.isPrimitive()) {
//primitive values cannot be null
return new HandyReturnValues().returnFor(returnType);
} else {
return result;
}
}
//boring delegation:
public MockCreationSettings getMockSettings() {
return delegate.getMockSettings();
}
public VoidMethodStubbable voidMethodStubbable(Object mock) {
return delegate.voidMethodStubbable(mock);
}
public void setAnswersForStubbing(List answers) {
delegate.setAnswersForStubbing(answers);
}
public InvocationContainer getInvocationContainer() {
return delegate.getInvocationContainer();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util;
import org.mockito.mock.MockName;
import java.io.Serializable;
public class MockNameImpl implements MockName, Serializable {
private static final long serialVersionUID = 8014974700844306925L;
private final String mockName;
private boolean defaultName;
@SuppressWarnings("unchecked")
public MockNameImpl(String mockName, Class classToMock) {
if (mockName == null) {
this.mockName = toInstanceName(classToMock);
this.defaultName = true;
} else {
this.mockName = mockName;
}
}
public MockNameImpl(String mockName) {
this.mockName = mockName;
}
private static String toInstanceName(Class<?> clazz) {
String className = clazz.getSimpleName();
if (className.length() == 0) {
//it's an anonymous class, let's get name from the parent
className = clazz.getSuperclass().getSimpleName();
}
//lower case first letter
return className.substring(0, 1).toLowerCase() + className.substring(1);
}
public boolean isDefault() {
return defaultName;
}
@Override
public String toString() {
return mockName;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.verification;
import org.mockito.internal.util.ObjectMethodsGuru;
import org.mockito.internal.util.collections.ListUtil;
import org.mockito.internal.util.collections.ListUtil.Filter;
import org.mockito.invocation.Invocation;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
public class DefaultRegisteredInvocations implements RegisteredInvocations, Serializable {
private static final long serialVersionUID = -2674402327380736290L;
private final LinkedList<Invocation> invocations = new LinkedList<Invocation>();
public void add(Invocation invocation) {
synchronized (invocations) {
invocations.add(invocation);
}
}
public void removeLast() {
//TODO: add specific test for synchronization of this block (it is tested by InvocationContainerImplTest at the moment)
synchronized (invocations) {
if (! invocations.isEmpty()) {
invocations.removeLast();
}
}
}
public List<Invocation> getAll() {
List<Invocation> copiedList;
synchronized (invocations) {
copiedList = new LinkedList<Invocation>(invocations) ;
}
return ListUtil.filter(copiedList, new RemoveToString());
}
public boolean isEmpty() {
synchronized (invocations) {
return invocations.isEmpty();
}
}
private static class RemoveToString implements Filter<Invocation> {
public boolean isOut(Invocation invocation) {
return new ObjectMethodsGuru().isToString(invocation.getMethod());
}
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> K> List<O> paramType_with_type_params();
* <S, T extends S> T two_type_params();
* <O extends K> O typeVar_with_type_params();
* Number returningNonGeneric();
* }
* </code></pre>
*
* @see #inferFrom(Type)
* @see #resolveGenericReturnType(Method)
* @see org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs
*/
@Incubating
public abstract class GenericMetadataSupport implements Serializable {
// public static MockitoLogger logger = new ConsoleMockitoLogger();
/**
* Represents actual type variables resolved for current class.
*/
protected Map<TypeVariable, Type> contextualActualTypeParameters = new HashMap<TypeVariable, Type>();
protected void registerTypeVariablesOn(Type classType) {
if (!(classType instanceof ParameterizedType)) {
return;
}
ParameterizedType parameterizedType = (ParameterizedType) classType;
TypeVariable[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParameters();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
for (int i = 0; i < actualTypeArguments.length; i++) {
TypeVariable typeParameter = typeParameters[i];
Type actualTypeArgument = actualTypeArguments[i];
if (actualTypeArgument instanceof WildcardType) {
contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument));
} else {
contextualActualTypeParameters.put(typeParameter, actualTypeArgument);
}
// logger.log("For '" + parameterizedType + "' found type variable : { '" + typeParameter + "(" + System.identityHashCode(typeParameter) + ")" + "' : '" + actualTypeArgument + "(" + System.identityHashCode(typeParameter) + ")" + "' }");
}
}
protected void registerTypeParametersOn(TypeVariable[] typeParameters) {
for (TypeVariable typeParameter : typeParameters) {
contextualActualTypeParameters.put(typeParameter, boundsOf(typeParameter));
// logger.log("For '" + typeParameter.getGenericDeclaration() + "' found type variable : { '" + type
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return typeVariable.equals(((TypeVarBoundedType) o).typeVariable);
}
@Override
public int hashCode() {
return typeVariable.hashCode();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("{firstBound=").append(firstBound());
sb.append(", interfaceBounds=").append(Arrays.deepToString(interfaceBounds()));
sb.append('}');
return sb.toString();
}
public TypeVariable typeVariable() {
return typeVariable;
}
}
/**
* Type representing bounds of a wildcard, allows to keep all bounds information.
*
* <p>The JLS says that lower bound and upper bound are mutually exclusive, and that multiple bounds
* are not allowed.
*
* @see <a href="http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4">http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4</a>
*/
public static class WildCardBoundedType implements BoundedType, Serializable {
private WildcardType wildcard;
public WildCardBoundedType(WildcardType wildcard) {
this.wildcard = wildcard;
}
/**
* @return The first bound, either a type or a reference to a TypeVariable
*/
public Type firstBound() {
Type[] lowerBounds = wildcard.getLowerBounds();
Type[] upperBounds = wildcard.getUpperBounds();
return lowerBounds.length != 0 ? lowerBounds[0] : upperBounds[0];
}
/**
* @return An empty array as, wildcard don't support multiple bounds.
*/
public Type[] interfaceBounds() {
return new Type[0];
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return wildcard.equals(((TypeVarBoundedType) o).typeVariable);
}
@Override
public int hashCode() {
return
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation;
import org.mockito.cglib.proxy.MethodInterceptor;
import org.mockito.cglib.proxy.MethodProxy;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.creation.cglib.CGLIBHacker;
import org.mockito.internal.invocation.InvocationImpl;
import org.mockito.internal.invocation.MockitoMethod;
import org.mockito.internal.invocation.SerializableMethod;
import org.mockito.internal.invocation.realmethod.FilteredCGLIBProxyRealMethod;
import org.mockito.internal.progress.SequenceNumber;
import org.mockito.internal.util.ObjectMethodsGuru;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
import java.io.Serializable;
import java.lang.reflect.Method;
/**
* Should be one instance per mock instance, see CglibMockMaker.
*
*
*/
public class MethodInterceptorFilter implements MethodInterceptor, Serializable {
private static final long serialVersionUID = 6182795666612683784L;
private final InternalMockHandler handler;
CGLIBHacker cglibHacker = new CGLIBHacker();
ObjectMethodsGuru objectMethodsGuru = new ObjectMethodsGuru();
private final MockCreationSettings mockSettings;
private AcrossJVMSerializationFeature acrossJVMSerializationFeature = new AcrossJVMSerializationFeature();
public MethodInterceptorFilter(InternalMockHandler handler, MockCreationSettings mockSettings) {
this.handler = handler;
this.mockSettings = mockSettings;
}
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)
throws Throwable {
if (objectMethodsGuru.isEqualsMethod(method)) {
return proxy == args[0];
} else if (objectMethodsGuru.isHashCodeMethod(method)) {
return hashCodeForMock(proxy);
} else if (acrossJVMSerializationFeature.isWriteReplace(method)) {
return acrossJVMSerializationFeature.writeReplace(proxy);
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>
MockitoMethodProxy mockitoMethodProxy = createMockitoMethodProxy(methodProxy);
cglibHacker.setMockitoNamingPolicy(mockitoMethodProxy);
MockitoMethod mockitoMethod = createMockitoMethod(method);
FilteredCGLIBProxyRealMethod realMethod = new FilteredCGLIBProxyRealMethod(mockitoMethodProxy);
Invocation invocation = new InvocationImpl(proxy, mockitoMethod, args, SequenceNumber.next(), realMethod);
return handler.handle(invocation);
}
public MockHandler getHandler() {
return handler;
}
private int hashCodeForMock(Object mock) {
return System.identityHashCode(mock);
}
public MockitoMethodProxy createMockitoMethodProxy(MethodProxy methodProxy) {
if (mockSettings.isSerializable())
return new SerializableMockitoMethodProxy(methodProxy);
return new DelegatingMockitoMethodProxy(methodProxy);
}
public MockitoMethod createMockitoMethod(Method method) {
if (mockSettings.isSerializable()) {
return new SerializableMethod(method);
} else {
return new DelegatingMethod(method);
}
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito;
import org.mockito.listeners.InvocationListener;
import org.mockito.mock.SerializableMode;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
/**
* Allows mock creation with additional mock settings.
* <p/>
* Don't use it too often.
* Consider writing simple tests that use simple mocks.
* Repeat after me: simple tests push simple, KISSy, readable & maintainable code.
* If you cannot write a test in a simple way - refactor the code under test.
* <p/>
* Examples of mock settings:
* <pre class="code"><code class="java">
* //Creates mock with different default answer & name
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie")
* );
*
* //Creates mock with different default answer, descriptive name and extra interfaces
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie")
* .extraInterfaces(Bar.class));
* </code></pre>
* {@link MockSettings} has been introduced for two reasons.
* Firstly, to make it easy to add another mock setting when the demand comes.
* Secondly, to enable combining together different mock settings without introducing zillions of overloaded mock() methods.
*/
public interface MockSettings extends Serializable {
/**
* Specifies extra interfaces the mock should implement. Might be useful for legacy code or some corner cases.
* For background, see issue 51 <a href="http://code.google.com/p/mockito/issues/detail?id=51">here</a>
* <p>
* This mysterious feature should be used very occasionally.
* The object under test should know exactly its collaborators & dependencies.
* If you happen to use it often than please make sure you are really producing simple, clean & readable code.
* <p>
*
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Enough warnings about partial mocks, see an example how spiedInstance() works:
* <pre class="code"><code class="java">
* Foo foo = mock(Foo.class, withSettings().spiedInstance(fooInstance));
*
* //Below does exactly the same:
* Foo foo = spy(fooInstance);
* </code></pre>
*
* About stubbing for a partial mock, as it is a spy it will always call the real method, unless you use the
* <code>doReturn</code>|<code>Throw</code>|<code>Answer</code>|<code>CallRealMethod</code> stubbing style. Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing
* doReturn("foo").when(spy).get(0);
* </code>
*
* @param instance to spy on
* @return settings instance so that you can fluently specify other settings
*/
MockSettings spiedInstance(Object instance);
/**
* Specifies default answers to interactions.
* It's quite advanced feature and typically you don't need it to write decent tests.
* However it can be helpful when working with legacy systems.
* <p>
* It is the default answer so it will be used <b>only when you don't</b> stub the method call.
*
* <pre class="code"><code class="java">
* Foo mock = mock
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>(Foo.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS));
* Foo mockTwo = mock(Foo.class, withSettings().defaultAnswer(new YourOwnAnswer()));
*
* //Below does exactly the same:
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
* </code></pre>
*
* @param defaultAnswer default answer to be used by mock when not stubbed
* @return settings instance so that you can fluently specify other settings
*/
@SuppressWarnings("unchecked")
MockSettings defaultAnswer(Answer defaultAnswer);
/**
* Configures the mock to be serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
* <p>
* WARNING: This should be rarely used in unit testing.
* <p>
* The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This
* was in a web environment and the objects from the external dependency were being serialized to pass between layers.
* <p>
* Example:
* <pre class="code"><code class="java">
* List serializableMock = mock(List.class, withSettings().serializable());
* </code></pre>
*
* @return settings instance so that you can fluently specify other settings
* @since 1.8.1
*/
MockSettings serializable();
/**
* Configures the mock to be serializable with a specific serializable mode.
* With this feature you can use a mock in a place that requires dependencies to be serializable.
* <p>
* WARNING: This should be rarely used in unit testing.
* <p>
* The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This
* was in a web environment and the objects from the external dependency were being serialized to pass between layers.
*
* <pre class="code"><code class="java">
* List serializableMock = mock(List.class, withSettings().serializable(SerializableMode.ACROSS_CLASSLOADERS));
* </code></pre>
*
* @param mode serialization mode
* @return settings instance so that you can fluently specify
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> other settings
* @since 1.9.8
*/
MockSettings serializable(SerializableMode mode);
/**
* Enables real-time logging of method invocations on this mock. Can be used
* during test debugging in order to find wrong interactions with this mock.
* <p>
* Invocations are logged as they happen to the standard output stream.
* <p>
* Calling this method multiple times makes no difference.
* <p>
* Example:
* <pre class="code"><code class="java">
* List mockWithLogger = mock(List.class, withSettings().verboseLogging());
* </code></pre>
*
* @return settings instance so that you can fluently specify other settings
*/
MockSettings verboseLogging();
/**
* Registers a listener for method invocations on this mock. The listener is
* notified every time a method on this mock is called.
* <p>
* Multiple listeners may be added, but the same object is only added once.
* The order, in which the listeners are added, is not guaranteed to be the
* order in which the listeners are notified.
*
* Example:
* <pre class="code"><code class="java">
* List mockWithListener = mock(List.class, withSettings().invocationListeners(new YourInvocationListener()));
* </code></pre>
*
* See the {@link InvocationListener listener interface} for more details.
*
* @param listeners The invocation listeners to add. May not be null.
* @return settings instance so that you can fluently specify other settings
*/
MockSettings invocationListeners(InvocationListener... listeners);
/**
* Sets whether this mock should only provide stubbing of methods.
* A stub-only mock does not record method
* invocations, thus saving memory but
* disallowing verification of invocations.
* <p>
* Example:
* <pre class="code"><code class="java">
* List stubOnly = mock(List.class, withSettings().stubOnly());
* </code></pre>
*
* @return settings instance so that you can fluently specify other settings
*/
MockSettings stubOnly();
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation.cglib;
import java.io.Serializable;
import java.lang.reflect.Field;
import org.mockito.internal.creation.MockitoMethodProxy;
import org.mockito.cglib.proxy.MethodProxy;
public class CGLIBHacker implements Serializable {
private static final long serialVersionUID = -4389233991416356668L;
public void setMockitoNamingPolicy(MockitoMethodProxy mockitoMethodProxy) {
try {
MethodProxy methodProxy = mockitoMethodProxy.getMethodProxy();
Field createInfoField = reflectOnCreateInfo(methodProxy);
createInfoField.setAccessible(true);
Object createInfo = createInfoField.get(methodProxy);
Field namingPolicyField = createInfo.getClass().getDeclaredField("namingPolicy");
namingPolicyField.setAccessible(true);
if (namingPolicyField.get(createInfo) == null) {
namingPolicyField.set(createInfo, MockitoNamingPolicy.INSTANCE);
}
} catch (Exception e) {
throw new RuntimeException(
"Unable to set MockitoNamingPolicy on cglib generator which creates FastClasses", e);
}
}
@SuppressWarnings("unchecked")
private Field reflectOnCreateInfo(MethodProxy methodProxy) throws SecurityException, NoSuchFieldException {
Class cglibMethodProxyClass = methodProxy.getClass();
// in case methodProxy was extended by user, let's traverse the object
// graph to find the cglib methodProxy
// with all the fields we would like to change
while (cglibMethodProxyClass != MethodProxy.class) {
cglibMethodProxyClass = methodProxy.getClass().getSuperclass();
}
return cglibMethodProxyClass.getDeclaredField("createInfo");
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation;
import org.mockito.cglib.proxy.Callback;
import org.mockito.cglib.proxy.Factory;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.InternalMockHandler;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
import org.mockito.plugins.MockMaker;
import org.mockito.internal.creation.jmock.ClassImposterizer;
/**
* A MockMaker that uses cglib to generate mocks on a JVM.
*/
public final class CglibMockMaker implements MockMaker {
public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
InternalMockHandler mockitoHandler = cast(handler);
new AcrossJVMSerializationFeature().enableSerializationAcrossJVM(settings);
return ClassImposterizer.INSTANCE.imposterise(
new MethodInterceptorFilter(mockitoHandler, settings), settings.getTypeToMock(), settings.getExtraInterfaces());
}
private InternalMockHandler cast(MockHandler handler) {
if (!(handler instanceof InternalMockHandler)) {
throw new MockitoException("At the moment you cannot provide own implementations of MockHandler." +
"\nPlease see the javadocs for the MockMaker interface.");
}
return (InternalMockHandler) handler;
}
public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {
((Factory) mock).setCallback(0, new MethodInterceptorFilter(cast(newHandler), settings));
}
public MockHandler getHandler(Object mock) {
if (!(mock instanceof Factory)) {
return null;
}
Factory factory = (Factory) mock;
Callback callback = factory.getCallback(0);
if (!(callback instanceof MethodInterceptorFilter)) {
return null;
}
return ((MethodInterceptorFilter) callback).getHandler();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.debugging;
import org.mockito.internal.exceptions.stacktrace.StackTraceFilter;
import org.mockito.invocation.Location;
import java.io.Serializable;
public class LocationImpl implements Location, Serializable {
private static final long serialVersionUID = -9054861157390980624L;
private final Throwable stackTraceHolder;
private final StackTraceFilter stackTraceFilter;
public LocationImpl() {
this(new StackTraceFilter());
}
public LocationImpl(StackTraceFilter stackTraceFilter) {
this.stackTraceFilter = stackTraceFilter;
stackTraceHolder = new Throwable();
}
@Override
public String toString() {
StackTraceElement[] filtered = stackTraceFilter.filter(stackTraceHolder.getStackTrace(), false);
if (filtered.length == 0) {
return "-> at <<unknown line>>";
}
return "-> at " + filtered[0].toString();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.creation;
import org.mockito.MockSettings;
import org.mockito.exceptions.Reporter;
import org.mockito.internal.creation.settings.CreationSettings;
import org.mockito.internal.debugging.VerboseMockInvocationLogger;
import org.mockito.internal.util.MockCreationValidator;
import org.mockito.internal.util.MockNameImpl;
import org.mockito.listeners.InvocationListener;
import org.mockito.mock.MockCreationSettings;
import org.mockito.mock.MockName;
import org.mockito.mock.SerializableMode;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.mockito.internal.util.collections.Sets.newSet;
@SuppressWarnings("unchecked")
public class MockSettingsImpl<T> extends CreationSettings<T> implements MockSettings, MockCreationSettings<T> {
private static final long serialVersionUID = 4475297236197939569L;
public MockSettings serializable() {
return serializable(SerializableMode.BASIC);
}
public MockSettings serializable(SerializableMode mode) {
this.serializableMode = mode;
return this;
}
public MockSettings extraInterfaces(Class... extraInterfaces) {
if (extraInterfaces == null || extraInterfaces.length == 0) {
new Reporter().extraInterfacesRequiresAtLeastOneInterface();
}
for (Class i : extraInterfaces) {
if (i == null) {
new Reporter().extraInterfacesDoesNotAcceptNullParameters();
} else if (!i.isInterface()) {
new Reporter().extraInterfacesAcceptsOnlyInterfaces(i);
}
}
this.extraInterfaces = newSet(extraInterfaces);
return this;
}
public MockName getMockName() {
return mockName;
}
public Set<Class> getExtraInterfaces() {
return extraInterfaces;
}
public Object getSpiedInstance() {
return spiedInstance;
}
public MockSettings name
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>(String name) {
this.name = name;
return this;
}
public MockSettings spiedInstance(Object spiedInstance) {
this.spiedInstance = spiedInstance;
return this;
}
public MockSettings defaultAnswer(Answer defaultAnswer) {
this.defaultAnswer = defaultAnswer;
if (defaultAnswer == null) {
new Reporter().defaultAnswerDoesNotAcceptNullParameter();
}
return this;
}
public Answer<Object> getDefaultAnswer() {
return defaultAnswer;
}
public MockSettingsImpl stubOnly() {
this.stubOnly = true;
return this;
}
public boolean isStubOnly() {
return this.stubOnly;
}
public MockSettings verboseLogging() {
if (!invocationListenersContainsType(VerboseMockInvocationLogger.class)) {
invocationListeners(new VerboseMockInvocationLogger());
}
return this;
}
public MockSettings invocationListeners(InvocationListener... listeners) {
if (listeners == null || listeners.length == 0) {
new Reporter().invocationListenersRequiresAtLeastOneListener();
}
for (InvocationListener listener : listeners) {
if (listener == null) {
new Reporter().invocationListenerDoesNotAcceptNullParameters();
}
this.invocationListeners.add(listener);
}
return this;
}
private boolean invocationListenersContainsType(Class<?> clazz) {
for (InvocationListener listener : invocationListeners) {
if (listener.getClass().equals(clazz)) {
return true;
}
}
return false;
}
public List<InvocationListener> getInvocationListeners() {
return this.invocationListeners;
}
public boolean hasInvocationListeners() {
return !invocationListeners.isEmpty();
}
public Class<T> getTypeToMock() {
return typeToMock;
}
public MockCreationSettings<T> confirm(Class<T> typeToMock) {
return validatedSettings(typeToMock, this);
}
private static <T> CreationSettings<T> validatedSettings(Class<T> typeToMock, CreationSettings<T> source) {
MockCreationValidator validator = new MockCreationValidator();
validator.validateType(typeToMock);
validator.validateExtraInterfaces(typeToMock, source.getExtraInterfaces());
validator.validateMockedType(type
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>ToMock, source.getSpiedInstance());
//TODO SF - add this validation and also add missing coverage
// validator.validateDelegatedInstance(classToMock, settings.getDelegatedInstance());
validator.validateSerializable(typeToMock, source.isSerializable());
CreationSettings<T> settings = new CreationSettings<T>(source);
settings.setMockName(new MockNameImpl(source.getName(), typeToMock));
settings.setTypeToMock(typeToMock);
settings.setExtraInterfaces(prepareExtraInterfaces(source));
return settings;
}
private static Set<Class> prepareExtraInterfaces(CreationSettings settings) {
Set<Class> interfaces = new HashSet<Class>(settings.getExtraInterfaces());
if(settings.isSerializable()) {
interfaces.add(Serializable.class);
}
return interfaces;
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.handler;
import org.mockito.exceptions.Reporter;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.invocation.MatchersBinder;
import org.mockito.internal.progress.MockingProgress;
import org.mockito.internal.progress.ThreadSafeMockingProgress;
import org.mockito.internal.stubbing.*;
import org.mockito.internal.verification.MockAwareVerificationMode;
import org.mockito.internal.verification.VerificationDataImpl;
import org.mockito.invocation.Invocation;
import org.mockito.mock.MockCreationSettings;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.VoidMethodStubbable;
import org.mockito.verification.VerificationMode;
import java.util.List;
/**
* Invocation handler set on mock objects.
*
* @param <T>
* type of mock object to handle
*/
class MockHandlerImpl<T> implements InternalMockHandler<T> {
private static final long serialVersionUID = -2917871070982574165L;
InvocationContainerImpl invocationContainerImpl;
MatchersBinder matchersBinder = new MatchersBinder();
MockingProgress mockingProgress = new ThreadSafeMockingProgress();
private final MockCreationSettings mockSettings;
public MockHandlerImpl(MockCreationSettings mockSettings) {
this.mockSettings = mockSettings;
this.mockingProgress = new ThreadSafeMockingProgress();
this.matchersBinder = new MatchersBinder();
this.invocationContainerImpl = new InvocationContainerImpl(mockingProgress, mockSettings);
}
public Object handle(Invocation invocation) throws Throwable {
if (invocationContainerImpl.hasAnswersForStubbing()) {
// stubbing voids with stubVoid() or doAnswer() style
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(
mockingProgress.getArgumentMatcherStorage(),
invocation
);
invocationContainerImpl.setMethodForStubbing(invocationMatcher);
return null;
}
VerificationMode verificationMode =
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> mockingProgress.pullVerificationMode();
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(
mockingProgress.getArgumentMatcherStorage(),
invocation
);
mockingProgress.validateState();
// if verificationMode is not null then someone is doing verify()
if (verificationMode != null) {
// We need to check if verification was started on the correct mock
// - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
if (((MockAwareVerificationMode) verificationMode).getMock() == invocation.getMock()) {
VerificationDataImpl data = createVerificationData(invocationContainerImpl, invocationMatcher);
verificationMode.verify(data);
return null;
} else {
// this means there is an invocation on a different mock. Re-adding verification mode
// - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
mockingProgress.verificationStarted(verificationMode);
}
}
// prepare invocation for stubbing
invocationContainerImpl.setInvocationForPotentialStubbing(invocationMatcher);
OngoingStubbingImpl<T> ongoingStubbing = new OngoingStubbingImpl<T>(invocationContainerImpl);
mockingProgress.reportOngoingStubbing(ongoingStubbing);
// look for existing answer for this invocation
StubbedInvocationMatcher stubbedInvocation = invocationContainerImpl.findAnswerFor(invocation);
if (stubbedInvocation != null) {
stubbedInvocation.captureArgumentsFrom(invocation);
return stubbedInvocation.answer(invocation);
} else {
Object ret = mockSettings.getDefaultAnswer().answer(invocation);
// redo setting invocation for potential stubbing in case of partial
// mocks / spies.
// Without it, the real method inside 'when' might have delegated
// to other self method and overwrite the intended stubbed method
// with a different one. The reset is required to avoid runtime exception that validates return type with stubbed method signature.
invocationContainerImpl.resetInvocationForPotentialStubbing(invocationMatcher);
return ret;
}
}
public VoidMethodStubbable<T> voidMethodStubbable(T mock) {
return new VoidMethodStubbableImpl<T>(mock, invocationContainerImpl);
}
public MockCreationSettings getMockSettings() {
return mockSettings;
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS> @SuppressWarnings("unchecked")
public void setAnswersForStubbing(List<Answer> answers) {
invocationContainerImpl.setAnswersForStubbing(answers);
}
public InvocationContainer getInvocationContainer() {
return invocationContainerImpl;
}
private VerificationDataImpl createVerificationData(InvocationContainerImpl invocationContainerImpl, InvocationMatcher invocationMatcher) {
if (mockSettings.isStubOnly()) {
new Reporter().stubPassedToVerify(); // this throws an exception
}
return new VerificationDataImpl(invocationContainerImpl, invocationMatcher);
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito;
public interface MockitoDebugger {
//Prints all interactions with mock. Also prints stubbing information.
//You can put it in your 'tearDown' method
String printInvocations(Object ... mocks);
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>package org.mockitousage.stubbing;
import static org.fest.assertions.Assertions.*;
import static org.mockito.Mockito.*;
import java.io.Serializable;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockitoutil.SimpleSerializationUtil;
public class DeepStubsSerializableTest {
public static final boolean STUBBED_BOOLEAN_VALUE = true;
public static final int STUBBED_INTEGER_VALUE = 999;
@Test
public void should_serialize_and_deserialize_mock_created_by_deep_stubs() throws Exception {
// given
SampleClass sampleClass = mock(SampleClass.class, withSettings().defaultAnswer(Mockito.RETURNS_DEEP_STUBS).serializable());
when(sampleClass.getSample().isSth()).thenReturn(STUBBED_BOOLEAN_VALUE);
when(sampleClass.getSample().getNumber()).thenReturn(STUBBED_INTEGER_VALUE);
// when
Object o = SimpleSerializationUtil.serializeAndBack(sampleClass);
// then
assertThat(o).isInstanceOf(SampleClass.class);
SampleClass deserializedSample = (SampleClass) o;
assertThat(deserializedSample.getSample().isSth()).isEqualTo(STUBBED_BOOLEAN_VALUE);
assertThat(deserializedSample.getSample().getNumber()).isEqualTo(STUBBED_INTEGER_VALUE);
}
class SampleClass implements Serializable {
SampleClass2 getSample() {
return new SampleClass2();
}
}
class SampleClass2 implements Serializable {
boolean isSth() {
return false;
}
int getNumber(){
return 100;
}
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.invocation.realmethod;
import org.mockito.internal.creation.MockitoMethodProxy;
import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
import java.io.Serializable;
public class FilteredCGLIBProxyRealMethod implements RealMethod, HasCGLIBMethodProxy, Serializable {
private static final long serialVersionUID = 3596550785818938496L;
private final RealMethod realMethod;
public FilteredCGLIBProxyRealMethod(MockitoMethodProxy methodProxy) {
this(new CGLIBProxyRealMethod(methodProxy));
}
public FilteredCGLIBProxyRealMethod(RealMethod realMethod) {
this.realMethod = realMethod;
}
public Object invoke(Object target, Object[] arguments) throws Throwable {
try {
return realMethod.invoke(target, arguments);
} catch (Throwable t) {
new ConditionalStackTraceFilter().filter(t);
throw t;
}
}
public MockitoMethodProxy getMethodProxy() {
return ((HasCGLIBMethodProxy) realMethod).getMethodProxy();
}
}
Mockito, 23
<FILEB>
<CHANGES>
private transient MockitoCore mockitoCore;
private transient ReturnsEmptyValues delegate;
<CHANGEE>
<CHANGES>
instantiateMockitoCoreIfNeeded();
instantiateDelegateIfNeeded();
<CHANGEE>
<CHANGES>
private synchronized void instantiateMockitoCoreIfNeeded() {
if (mockitoCore == null) {
mockitoCore = new MockitoCore();
}
}
private synchronized void instantiateDelegateIfNeeded() {
if (delegate == null) {
delegate = new ReturnsEmptyValues();
}
}
<CHANGEE>
<CHANGES>
.serializable()
<CHANGEE>
<CHANGES>
container.addAnswer(new SerializableAnswer() {
<CHANGEE>
<CHANGES>
abstract class SerializableAnswer implements Answer<Object>, Serializable {
}
<CHANGEE>
<FILEE>
<FILEB>
*
* Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
* <pre class="code"><code class="java">
* interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
*
* GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
* Number number = mock.entrySet().iterator().next().getValue().iterator().next();
* </code></pre>
* </p>
*
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
public class ReturnsDeepStubs implements Answer<Object>, Serializable {
private static final long serialVersionUID = -7105341425736035847L;
<CHANGES>
private MockitoCore mockitoCore = new MockitoCore();
private ReturnsEmptyValues delegate = new ReturnsEmptyValues();
<CHANGEE>
public Object answer(InvocationOnMock invocation) throws Throwable {
GenericMetadataSupport returnTypeGenericMetadata =
actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
Class<?> rawType = returnTypeGenericMetadata.rawType();
<CHANGES>
<CHANGEE>
if (!mockitoCore.isTypeMockable(rawType)) {
return delegate.returnValueFor(rawType);
}
return getMock(invocation, returnTypeGenericMetadata);
}
<CHANGES>
<CHANGEE>
private Object getMock(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock());
InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
// matches invocation for verification
for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
return stubbedInvocationMatcher.answer(invocation);
}
}
// deep stub
return recordDeepStubMock(<SCANS>/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.invocation;
import org.mockito.Incubating;
/**
* A method call on a mock object. Contains all information and state needed for the Mockito framework to operate.
* This API might be useful for developers who extend Mockito.
* <p>
* The javadoc does not have lots of examples or documentation because its audience is different.
* Vast majority of users don't need to use the Invocation. It's mostly useful for other framework authors
* that extend Mockito.
*
* @since 1.9.5
*/
@Incubating
public interface Invocation extends InvocationOnMock, DescribedInvocation {
/**
* @return whether the invocation has been already verified.
* Needed for {@link org.mockito.Mockito#verifyNoMoreInteractions(Object...)}
*/
boolean isVerified();
/**
* @return the sequence number of the Invocation. Useful to determine the order of invocations.
* Used by verification in order.
*/
int getSequenceNumber();
/**
* @return the location in code of this invocation.
*/
Location getLocation();
/**
* Returns unprocessed arguments whereas {@link #getArguments()} returns
* arguments already processed (e.g. varargs expended, etc.).
*
* @return unprocessed arguments, exactly as provided to this invocation.
*/
Object[] getRawArguments();
/**
* Marks this invocation as verified so that it will not cause verification error at
* {@link org.mockito.Mockito#verifyNoMoreInteractions(Object...)}
*/
void markVerified();
/**
* @return the stubbing information for this invocation. May return null - this means
* the invocation was not stubbed.
*/
StubInfo stubInfo();
/**
* Marks this invocation as stubbed.
*
* @param stubInfo the information about stubbing.
*/
void markStubbed(StubInfo stubInfo);
/**
* Informs if the invocation participates in verify-no-more-invocations or verification in order.
*
* @return whether this invocation should be ignored for the purposes of
* verify-no-more-invocations or verification in order.
*/